Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php // http://stackoverflow.com/questions/31470421/recursivedirectoryiterator-indent-subfolders
- class SortedDirectory implements IteratorAggregate, Countable
- {
- /**
- * Sorted directory list
- *
- * @var array
- */
- private $directories = array();
- /**
- * sorted file list
- *
- * @var array
- */
- private $files = array();
- private $allFiles = null;
- /**
- * Read the supplied directory into the two lists and sort them
- *
- * Ignore the '.' and '..' entries
- *
- * @param SplFileInfo
- */
- public function __construct(\SplFileInfo $directory)
- {
- foreach (new DirectoryIterator($directory->getRealPath()) as $entry) {
- if ($entry->isDir()) {
- $fname = $entry->getBasename();
- if (substr($fname, 0, 1) === '.') {
- if ($fname === '.' || $fname === '..') {
- continue;
- }
- }
- $this->directories[] = clone $entry;
- }
- else {
- $this->files[] = clone $entry;
- }
- }
- $this->sortLists();
- }
- /**
- * Iterator of the sorted directory list
- *
- * @return \ArrayIterator
- */
- public function getDirIterator()
- {
- return new ArrayIterator($this->directories);
- }
- /**
- * Iterator of the sorted files
- *
- * @return \ArrayIterator
- */
- public function getFileIterator()
- {
- return new ArrayIterator($this->files);
- }
- /**
- * Iterator of all the directory entries
- *
- * @return \ArrayIterator All the files with directories before files
- */
- public function getIterator()
- {
- return new ArrayIterator($this->allFiles);
- }
- public function __get($property)
- {
- return $this->$property;
- }
- /*
- * Implement Iterator
- *
- */
- /**
- * @return \SplFileInfo
- */
- public function current()
- {
- return current($this->allFiles);
- }
- /**
- * @return int
- */
- public function key()
- {
- return key($this->allFiles);
- }
- public function next()
- {
- return next($this->allFiles);
- }
- public function reset()
- {
- return reset($this->allFiles);
- }
- public function rewind()
- {
- return reset($this->allFiles);
- }
- public function valid()
- {
- return current($this->allFiles) !== false;
- }
- /**
- * @return integer
- */
- public function count()
- {
- return count($this->allFiles);
- }
- /**
- * Sort lists using 'natural' compare
- */
- private function sortLists()
- {
- if (count($this->directories) >= 2) {
- usort($this->directories, array($this, 'cmpEntry'));
- }
- if (count($this->files) >= 2) {
- usort($this->files, array($this, 'cmpEntry'));
- }
- $this->allFiles = array_merge($this->directories, $this->files);
- }
- private function cmpEntry(SplFileInfo $entry1, SplFileInfo $entry2)
- {
- return strnatcasecmp($entry1->getFilename(), $entry2->getFilename());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement