1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Symfony\Component\Finder\Iterator;
13:
14: 15: 16: 17: 18:
19: class SortableIterator implements \IteratorAggregate
20: {
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;
26:
27: private $iterator;
28: private $sort;
29:
30: 31: 32: 33: 34: 35: 36: 37:
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 callback 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: }
83: