Created
March 21, 2022 15:28
-
-
Save coisa/b43b5f3d4b0522cb10cd6bab8d7dd701 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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