DirectoryListing.php 1.9 KB

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