ExcludeIterator.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of phpunit/php-file-iterator.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\FileIterator;
  11. use function assert;
  12. use function str_starts_with;
  13. use RecursiveDirectoryIterator;
  14. use RecursiveFilterIterator;
  15. use SplFileInfo;
  16. /**
  17. * @internal This class is not covered by the backward compatibility promise for phpunit/php-file-iterator
  18. */
  19. final class ExcludeIterator extends RecursiveFilterIterator
  20. {
  21. /**
  22. * @psalm-var list<string>
  23. */
  24. private array $exclude;
  25. /**
  26. * @psalm-param list<string> $exclude
  27. */
  28. public function __construct(RecursiveDirectoryIterator $iterator, array $exclude)
  29. {
  30. parent::__construct($iterator);
  31. $this->exclude = $exclude;
  32. }
  33. public function accept(): bool
  34. {
  35. $current = $this->current();
  36. assert($current instanceof SplFileInfo);
  37. $path = $current->getRealPath();
  38. if ($path === false) {
  39. return false;
  40. }
  41. foreach ($this->exclude as $exclude) {
  42. if (str_starts_with($path, $exclude)) {
  43. return false;
  44. }
  45. }
  46. return true;
  47. }
  48. public function hasChildren(): bool
  49. {
  50. return $this->getInnerIterator()->hasChildren();
  51. }
  52. public function getChildren(): self
  53. {
  54. return new self(
  55. $this->getInnerIterator()->getChildren(),
  56. $this->exclude
  57. );
  58. }
  59. public function getInnerIterator(): RecursiveDirectoryIterator
  60. {
  61. $innerIterator = parent::getInnerIterator();
  62. assert($innerIterator instanceof RecursiveDirectoryIterator);
  63. return $innerIterator;
  64. }
  65. }