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;
31 * @param \Traversable $iterator The Iterator to filter
32 * @param int|callable $sort The sort type (SORT_BY_NAME, SORT_BY_TYPE, or a PHP callback)
34 * @throws \InvalidArgumentException
36 public function __construct(\Traversable $iterator, $sort)
38 $this->iterator = $iterator;
40 if (self::SORT_BY_NAME === $sort) {
41 $this->sort = function ($a, $b) {
42 return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
44 } elseif (self::SORT_BY_TYPE === $sort) {
45 $this->sort = function ($a, $b) {
46 if ($a->isDir() && $b->isFile()) {
48 } elseif ($a->isFile() && $b->isDir()) {
52 return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
54 } elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
55 $this->sort = function ($a, $b) {
56 return $a->getATime() - $b->getATime();
58 } elseif (self::SORT_BY_CHANGED_TIME === $sort) {
59 $this->sort = function ($a, $b) {
60 return $a->getCTime() - $b->getCTime();
62 } elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
63 $this->sort = function ($a, $b) {
64 return $a->getMTime() - $b->getMTime();
66 } elseif (is_callable($sort)) {
69 throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
73 public function getIterator()
75 $array = iterator_to_array($this->iterator, true);
76 uasort($array, $this->sort);
78 return new \ArrayIterator($array);