/src/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php

https://github.com/pulzarraider/symfony · PHP · 84 lines · 50 code · 12 blank · 22 comment · 9 complexity · c312b4bbc3201b51d545a06e7e0058ec MD5 · raw file

  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Finder\Iterator;
  11. /**
  12. * ExcludeDirectoryFilterIterator filters out directories.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class ExcludeDirectoryFilterIterator extends \FilterIterator implements \RecursiveIterator
  17. {
  18. private $iterator;
  19. private $isRecursive;
  20. private $excludedDirs = [];
  21. private $excludedPattern;
  22. /**
  23. * @param \Iterator $iterator The Iterator to filter
  24. * @param array $directories An array of directories to exclude
  25. */
  26. public function __construct(\Iterator $iterator, array $directories)
  27. {
  28. $this->iterator = $iterator;
  29. $this->isRecursive = $iterator instanceof \RecursiveIterator;
  30. $patterns = [];
  31. foreach ($directories as $directory) {
  32. $directory = rtrim($directory, '/');
  33. if (!$this->isRecursive || false !== strpos($directory, '/')) {
  34. $patterns[] = preg_quote($directory, '#');
  35. } else {
  36. $this->excludedDirs[$directory] = true;
  37. }
  38. }
  39. if ($patterns) {
  40. $this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#';
  41. }
  42. parent::__construct($iterator);
  43. }
  44. /**
  45. * Filters the iterator values.
  46. *
  47. * @return bool True if the value should be kept, false otherwise
  48. */
  49. public function accept()
  50. {
  51. if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) {
  52. return false;
  53. }
  54. if ($this->excludedPattern) {
  55. $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath();
  56. $path = str_replace('\\', '/', $path);
  57. return !preg_match($this->excludedPattern, $path);
  58. }
  59. return true;
  60. }
  61. public function hasChildren()
  62. {
  63. return $this->isRecursive && $this->iterator->hasChildren();
  64. }
  65. public function getChildren()
  66. {
  67. $children = new self($this->iterator->getChildren(), []);
  68. $children->excludedDirs = $this->excludedDirs;
  69. $children->excludedPattern = $this->excludedPattern;
  70. return $children;
  71. }
  72. }