TYPO3  7.6
SortableIterator.php
Go to the documentation of this file.
1 <?php
2 
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11 
12 namespace Symfony\Component\Finder\Iterator;
13 
19 class SortableIterator implements \IteratorAggregate
20 {
21  const SORT_BY_NAME = 1;
22  const SORT_BY_TYPE = 2;
26 
27  private $iterator;
28  private $sort;
29 
38  public function __construct(\Traversable $iterator, $sort)
39  {
40  $this->iterator = $iterator;
41 
42  if (self::SORT_BY_NAME === $sort) {
43  $this->sort = function ($a, $b) {
44  return strcmp($a->getRealpath(), $b->getRealpath());
45  };
46  } elseif (self::SORT_BY_TYPE === $sort) {
47  $this->sort = function ($a, $b) {
48  if ($a->isDir() && $b->isFile()) {
49  return -1;
50  } elseif ($a->isFile() && $b->isDir()) {
51  return 1;
52  }
53 
54  return strcmp($a->getRealpath(), $b->getRealpath());
55  };
56  } elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
57  $this->sort = function ($a, $b) {
58  return ($a->getATime() - $b->getATime());
59  };
60  } elseif (self::SORT_BY_CHANGED_TIME === $sort) {
61  $this->sort = function ($a, $b) {
62  return ($a->getCTime() - $b->getCTime());
63  };
64  } elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
65  $this->sort = function ($a, $b) {
66  return ($a->getMTime() - $b->getMTime());
67  };
68  } elseif (is_callable($sort)) {
69  $this->sort = $sort;
70  } else {
71  throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
72  }
73  }
74 
75  public function getIterator()
76  {
77  $array = iterator_to_array($this->iterator, true);
78  uasort($array, $this->sort);
79 
80  return new \ArrayIterator($array);
81  }
82 }