4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Finder\Iterator;
15 * SortableIterator applies a sort on a given Iterator.
17 * @author Fabien Potencier <fabien@symfony.com>
19 class SortableIterator implements \IteratorAggregate
21 const SORT_BY_NAME = 1;
22 const SORT_BY_TYPE = 2;
23 const SORT_BY_ACCESSED_TIME = 3;
24 const SORT_BY_CHANGED_TIME = 4;
25 const SORT_BY_MODIFIED_TIME = 5;
33 * @param \Traversable $iterator The Iterator to filter
34 * @param int|callable $sort The sort type (SORT_BY_NAME, SORT_BY_TYPE, or a PHP callback)
36 * @throws \InvalidArgumentException
38 public function __construct(\Traversable $iterator, $sort)
40 $this->iterator = $iterator;
42 if (self::SORT_BY_NAME === $sort) {
43 $this->sort = function ($a, $b) {
44 return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
46 } elseif (self::SORT_BY_TYPE === $sort) {
47 $this->sort = function ($a, $b) {
48 if ($a->isDir() && $b->isFile()) {
50 } elseif ($a->isFile() && $b->isDir()) {
54 return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
56 } elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
57 $this->sort = function ($a, $b) {
58 return $a->getATime() - $b->getATime();
60 } elseif (self::SORT_BY_CHANGED_TIME === $sort) {
61 $this->sort = function ($a, $b) {
62 return $a->getCTime() - $b->getCTime();
64 } elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
65 $this->sort = function ($a, $b) {
66 return $a->getMTime() - $b->getMTime();
68 } elseif (is_callable($sort)) {
71 throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
75 public function getIterator()
77 $array = iterator_to_array($this->iterator, true);
78 uasort($array, $this->sort);
80 return new \ArrayIterator($array);