| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace League\Flysystem; |
| 6 |
|
| 7 |
use ArrayIterator; |
| 8 |
use Generator; |
| 9 |
use IteratorAggregate; |
| 10 |
use Traversable; |
| 11 |
|
| 12 |
/** |
| 13 |
* @template T |
| 14 |
*/ |
| 15 |
class DirectoryListing implements IteratorAggregate |
| 16 |
{ |
| 17 |
/** |
| 18 |
* @param iterable<T> $listing |
| 19 |
*/ |
| 20 |
public function __construct(private iterable $listing) |
| 21 |
{ |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* @param callable(T): bool $filter |
| 26 |
* |
| 27 |
* @return DirectoryListing<T> |
| 28 |
*/ |
| 29 |
public function filter(callable $filter): DirectoryListing |
| 30 |
{ |
| 31 |
$generator = (static function (iterable $listing) use ($filter): Generator { |
| 32 |
foreach ($listing as $item) { |
| 33 |
if ($filter($item)) { |
| 34 |
yield $item; |
| 35 |
} |
| 36 |
} |
| 37 |
})($this->listing); |
| 38 |
|
| 39 |
return new DirectoryListing($generator); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* @template R |
| 44 |
* |
| 45 |
* @param callable(T): R $mapper |
| 46 |
* |
| 47 |
* @return DirectoryListing<R> |
| 48 |
*/ |
| 49 |
public function map(callable $mapper): DirectoryListing |
| 50 |
{ |
| 51 |
$generator = (static function (iterable $listing) use ($mapper): Generator { |
| 52 |
foreach ($listing as $item) { |
| 53 |
yield $mapper($item); |
| 54 |
} |
| 55 |
})($this->listing); |
| 56 |
|
| 57 |
return new DirectoryListing($generator); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* @return DirectoryListing<T> |
| 62 |
*/ |
| 63 |
public function sortByPath(): DirectoryListing |
| 64 |
{ |
| 65 |
$listing = $this->toArray(); |
| 66 |
|
| 67 |
usort($listing, function (StorageAttributes $a, StorageAttributes $b) { |
| 68 |
return $a->path() <=> $b->path(); |
| 69 |
}); |
| 70 |
|
| 71 |
return new DirectoryListing($listing); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* @return Traversable<T> |
| 76 |
*/ |
| 77 |
public function getIterator(): Traversable |
| 78 |
{ |
| 79 |
return $this->listing instanceof Traversable |
| 80 |
? $this->listing |
| 81 |
: new ArrayIterator($this->listing); |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* @return T[] |
| 86 |
*/ |
| 87 |
public function toArray(): array |
| 88 |
{ |
| 89 |
return $this->listing instanceof Traversable |
| 90 |
? iterator_to_array($this->listing, false) |
| 91 |
: (array) $this->listing; |
| 92 |
} |
| 93 |
} |
| 94 |
|