Skip to content

Instantly share code, notes, and snippets.

@coisa
Created March 21, 2022 15:28
Show Gist options
  • Select an option

  • Save coisa/b43b5f3d4b0522cb10cd6bab8d7dd701 to your computer and use it in GitHub Desktop.

Select an option

Save coisa/b43b5f3d4b0522cb10cd6bab8d7dd701 to your computer and use it in GitHub Desktop.
<?php
namespace CoiSA\Iterator;
use FilesystemIterator;
use FilterIterator;
use IteratorIterator;
use RecursiveIterator;
use RecursiveIteratorIterator;
/**
* Defines a filter iterator that only accepts files of a certain type.
*
* @package CoiSA\Iterator
*/
final class FileTypeFilterIterator extends FilterIterator
{
/**
* The file extensions to accept.
*
* @var string[]
*/
private $fileTypes;
/**
* FileTypeFilterIterator constructor.
*
* @param FilesystemIterator $iterator The file system iterator to filter.
* @param array $fileTypes The file extensions to accept.
*/
public function __construct(FilesystemIterator $iterator, array $fileTypes)
{
$this->fileTypes = array_map(function ($fileType) {
return ltrim($fileType, '.');
}, $fileTypes);
$innerIterator = $iterator instanceof RecursiveIterator
? new RecursiveIteratorIterator($iterator)
: new IteratorIterator($iterator);
parent::__construct($innerIterator);
}
/**
* @inheritDoc
*/
public function accept()
{
$current = $this->current();
if ($current->isDir()) {
return $this->getInnerIterator() instanceof RecursiveIterator;
}
$extension = pathinfo($current->getFilename(), PATHINFO_EXTENSION);
return in_array($extension, $this->fileTypes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment