Debian Codegraph @

vendor/symfony/finder/Finder.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Finder;
13
14 use Symfony\Component\Finder\Comparator\DateComparator;
15 use Symfony\Component\Finder\Comparator\NumberComparator;
16 use Symfony\Component\Finder\Exception\DirectoryNotFoundException;
17 use Symfony\Component\Finder\Iterator\CustomFilterIterator;
18 use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
19 use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
20 use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
21 use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
22 use Symfony\Component\Finder\Iterator\FilenameFilterIterator;
23 use Symfony\Component\Finder\Iterator\LazyIterator;
24 use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
25 use Symfony\Component\Finder\Iterator\SortableIterator;
26
27 /**
28 * Finder allows to build rules to find files and directories.
29 *
30 * It is a thin wrapper around several specialized iterator classes.
31 *
32 * All rules may be invoked several times.
33 *
34 * All methods return the current Finder object to allow chaining:
35 *
36 * $finder = Finder::create()->files()->name('*.php')->in(__DIR__);
37 *
38 * @author Fabien Potencier <[email protected]>
39 *
40 * @implements \IteratorAggregate<non-empty-string, SplFileInfo>
41 */
42 class Finder implements \IteratorAggregate, \Countable
43 {
44 public const IGNORE_VCS_FILES = 1;
45 public const IGNORE_DOT_FILES = 2;
46 public const IGNORE_VCS_IGNORED_FILES = 4;
47
48 private int $mode = 0;
49 private array $names = [];
50 private array $notNames = [];
51 private array $exclude = [];
52 private array $filters = [];
53 private array $pruneFilters = [];
54 private array $depths = [];
55 private array $sizes = [];
56 private bool $followLinks = false;
57 private bool $reverseSorting = false;
58 private \Closure|int|false $sort = false;
59 private int $ignore = 0;
60 /** @var list<string> */
61 private array $dirs = [];
62 private array $dates = [];
63 /** @var list<iterable<SplFileInfo|\SplFileInfo|string>> */
64 private array $iterators = [];
65 private array $contains = [];
66 private array $notContains = [];
67 private array $paths = [];
68 private array $notPaths = [];
69 private bool $ignoreUnreadableDirs = false;
70
71 private static array $vcsPatterns = ['.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg'];
72
73 public function __construct()
74 {
75 $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
76 }
77
78 /**
79 * Creates a new Finder.
80 */
81 public static function create(): static
82 {
83 return new static();
84 }
85
86 /**
87 * Restricts the matching to directories only.
88 *
89 * @return $this
90 */
91 public function directories(): static
92 {
93 $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
94
95 return $this;
96 }
97
98 /**
99 * Restricts the matching to files only.
100 *
101 * @return $this
102 */
103 public function files(): static
104 {
105 $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
106
107 return $this;
108 }
109
110 /**
111 * Adds tests for the directory depth.
112 *
113 * Usage:
114 *
115 * $finder->depth('> 1') // the Finder will start matching at level 1.
116 * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point.
117 * $finder->depth(['>= 1', '< 3'])
118 *
119 * @param string|int|string[]|int[] $levels The depth level expression or an array of depth levels
120 *
121 * @return $this
122 *
123 * @see DepthRangeFilterIterator
124 * @see NumberComparator
125 */
126 public function depth(string|int|array $levels): static
127 {
128 foreach ((array) $levels as $level) {
129 $this->depths[] = new NumberComparator($level);
130 }
131
132 return $this;
133 }
134
135 /**
136 * Adds tests for file dates (last modified).
137 *
138 * The date must be something that strtotime() is able to parse:
139 *
140 * $finder->date('since yesterday');
141 * $finder->date('until 2 days ago');
142 * $finder->date('> now - 2 hours');
143 * $finder->date('>= 2005-10-15');
144 * $finder->date(['>= 2005-10-15', '<= 2006-05-27']);
145 *
146 * @param string|string[] $dates A date range string or an array of date ranges
147 *
148 * @return $this
149 *
150 * @see strtotime
151 * @see DateRangeFilterIterator
152 * @see DateComparator
153 */
154 public function date(string|array $dates): static
155 {
156 foreach ((array) $dates as $date) {
157 $this->dates[] = new DateComparator($date);
158 }
159
160 return $this;
161 }
162
163 /**
164 * Adds rules that files must match.
165 *
166 * You can use patterns (delimited with / sign), globs or simple strings.
167 *
168 * $finder->name('/\.php$/')
169 * $finder->name('*.php') // same as above, without dot files
170 * $finder->name('test.php')
171 * $finder->name(['test.py', 'test.php'])
172 *
173 * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns
174 *
175 * @return $this
176 *
177 * @see FilenameFilterIterator
178 */
179 public function name(string|array $patterns): static
180 {
181 $this->names = array_merge($this->names, (array) $patterns);
182
183 return $this;
184 }
185
186 /**
187 * Adds rules that files must not match.
188 *
189 * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns
190 *
191 * @return $this
192 *
193 * @see FilenameFilterIterator
194 */
195 public function notName(string|array $patterns): static
196 {
197 $this->notNames = array_merge($this->notNames, (array) $patterns);
198
199 return $this;
200 }
201
202 /**
203 * Adds tests that file contents must match.
204 *
205 * Strings or PCRE patterns can be used:
206 *
207 * $finder->contains('Lorem ipsum')
208 * $finder->contains('/Lorem ipsum/i')
209 * $finder->contains(['dolor', '/ipsum/i'])
210 *
211 * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns
212 *
213 * @return $this
214 *
215 * @see FilecontentFilterIterator
216 */
217 public function contains(string|array $patterns): static
218 {
219 $this->contains = array_merge($this->contains, (array) $patterns);
220
221 return $this;
222 }
223
224 /**
225 * Adds tests that file contents must not match.
226 *
227 * Strings or PCRE patterns can be used:
228 *
229 * $finder->notContains('Lorem ipsum')
230 * $finder->notContains('/Lorem ipsum/i')
231 * $finder->notContains(['lorem', '/dolor/i'])
232 *
233 * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns
234 *
235 * @return $this
236 *
237 * @see FilecontentFilterIterator
238 */
239 public function notContains(string|array $patterns): static
240 {
241 $this->notContains = array_merge($this->notContains, (array) $patterns);
242
243 return $this;
244 }
245
246 /**
247 * Adds rules that filenames must match.
248 *
249 * You can use patterns (delimited with / sign) or simple strings.
250 *
251 * $finder->path('some/special/dir')
252 * $finder->path('/some\/special\/dir/') // same as above
253 * $finder->path(['some dir', 'another/dir'])
254 *
255 * Use only / as dirname separator.
256 *
257 * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns
258 *
259 * @return $this
260 *
261 * @see FilenameFilterIterator
262 */
263 public function path(string|array $patterns): static
264 {
265 $this->paths = array_merge($this->paths, (array) $patterns);
266
267 return $this;
268 }
269
270 /**
271 * Adds rules that filenames must not match.
272 *
273 * You can use patterns (delimited with / sign) or simple strings.
274 *
275 * $finder->notPath('some/special/dir')
276 * $finder->notPath('/some\/special\/dir/') // same as above
277 * $finder->notPath(['some/file.txt', 'another/file.log'])
278 *
279 * Use only / as dirname separator.
280 *
281 * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns
282 *
283 * @return $this
284 *
285 * @see FilenameFilterIterator
286 */
287 public function notPath(string|array $patterns): static
288 {
289 $this->notPaths = array_merge($this->notPaths, (array) $patterns);
290
291 return $this;
292 }
293
294 /**
295 * Adds tests for file sizes.
296 *
297 * $finder->size('> 10K');
298 * $finder->size('<= 1Ki');
299 * $finder->size(4);
300 * $finder->size(['> 10K', '< 20K'])
301 *
302 * @param string|int|string[]|int[] $sizes A size range string or an integer or an array of size ranges
303 *
304 * @return $this
305 *
306 * @see SizeRangeFilterIterator
307 * @see NumberComparator
308 */
309 public function size(string|int|array $sizes): static
310 {
311 foreach ((array) $sizes as $size) {
312 $this->sizes[] = new NumberComparator($size);
313 }
314
315 return $this;
316 }
317
318 /**
319 * Excludes directories.
320 *
321 * Directories passed as argument must be relative to the ones defined with the `in()` method. For example:
322 *
323 * $finder->in(__DIR__)->exclude('ruby');
324 *
325 * @param string|array $dirs A directory path or an array of directories
326 *
327 * @return $this
328 *
329 * @see ExcludeDirectoryFilterIterator
330 */
331 public function exclude(string|array $dirs): static
332 {
333 $this->exclude = array_merge($this->exclude, (array) $dirs);
334
335 return $this;
336 }
337
338 /**
339 * Excludes "hidden" directories and files (starting with a dot).
340 *
341 * This option is enabled by default.
342 *
343 * @return $this
344 *
345 * @see ExcludeDirectoryFilterIterator
346 */
347 public function ignoreDotFiles(bool $ignoreDotFiles): static
348 {
349 if ($ignoreDotFiles) {
350 $this->ignore |= static::IGNORE_DOT_FILES;
351 } else {
352 $this->ignore &= ~static::IGNORE_DOT_FILES;
353 }
354
355 return $this;
356 }
357
358 /**
359 * Forces the finder to ignore version control directories.
360 *
361 * This option is enabled by default.
362 *
363 * @return $this
364 *
365 * @see ExcludeDirectoryFilterIterator
366 */
367 public function ignoreVCS(bool $ignoreVCS): static
368 {
369 if ($ignoreVCS) {
370 $this->ignore |= static::IGNORE_VCS_FILES;
371 } else {
372 $this->ignore &= ~static::IGNORE_VCS_FILES;
373 }
374
375 return $this;
376 }
377
378 /**
379 * Forces Finder to obey .gitignore and ignore files based on rules listed there.
380 *
381 * This option is disabled by default.
382 *
383 * @return $this
384 */
385 public function ignoreVCSIgnored(bool $ignoreVCSIgnored): static
386 {
387 if ($ignoreVCSIgnored) {
388 $this->ignore |= static::IGNORE_VCS_IGNORED_FILES;
389 } else {
390 $this->ignore &= ~static::IGNORE_VCS_IGNORED_FILES;
391 }
392
393 return $this;
394 }
395
396 /**
397 * Adds VCS patterns.
398 *
399 * @see ignoreVCS()
400 *
401 * @param string|string[] $pattern VCS patterns to ignore
402 */
403 public static function addVCSPattern(string|array $pattern): void
404 {
405 foreach ((array) $pattern as $p) {
406 self::$vcsPatterns[] = $p;
407 }
408
409 self::$vcsPatterns = array_unique(self::$vcsPatterns);
410 }
411
412 /**
413 * Sorts files and directories by an anonymous function.
414 *
415 * The anonymous function receives two \SplFileInfo instances to compare.
416 *
417 * This can be slow as all the matching files and directories must be retrieved for comparison.
418 *
419 * @return $this
420 *
421 * @see SortableIterator
422 */
423 public function sort(\Closure $closure): static
424 {
425 $this->sort = $closure;
426
427 return $this;
428 }
429
430 /**
431 * Sorts files and directories by extension.
432 *
433 * This can be slow as all the matching files and directories must be retrieved for comparison.
434 *
435 * @return $this
436 *
437 * @see SortableIterator
438 */
439 public function sortByExtension(): static
440 {
441 $this->sort = SortableIterator::SORT_BY_EXTENSION;
442
443 return $this;
444 }
445
446 /**
447 * Sorts files and directories by name.
448 *
449 * This can be slow as all the matching files and directories must be retrieved for comparison.
450 *
451 * @return $this
452 *
453 * @see SortableIterator
454 */
455 public function sortByName(bool $useNaturalSort = false): static
456 {
457 $this->sort = $useNaturalSort ? SortableIterator::SORT_BY_NAME_NATURAL : SortableIterator::SORT_BY_NAME;
458
459 return $this;
460 }
461
462 /**
463 * Sorts files and directories by name case insensitive.
464 *
465 * This can be slow as all the matching files and directories must be retrieved for comparison.
466 *
467 * @return $this
468 *
469 * @see SortableIterator
470 */
471 public function sortByCaseInsensitiveName(bool $useNaturalSort = false): static
472 {
473 $this->sort = $useNaturalSort ? SortableIterator::SORT_BY_NAME_NATURAL_CASE_INSENSITIVE : SortableIterator::SORT_BY_NAME_CASE_INSENSITIVE;
474
475 return $this;
476 }
477
478 /**
479 * Sorts files and directories by size.
480 *
481 * This can be slow as all the matching files and directories must be retrieved for comparison.
482 *
483 * @return $this
484 *
485 * @see SortableIterator
486 */
487 public function sortBySize(): static
488 {
489 $this->sort = SortableIterator::SORT_BY_SIZE;
490
491 return $this;
492 }
493
494 /**
495 * Sorts files and directories by type (directories before files), then by name.
496 *
497 * This can be slow as all the matching files and directories must be retrieved for comparison.
498 *
499 * @return $this
500 *
501 * @see SortableIterator
502 */
503 public function sortByType(): static
504 {
505 $this->sort = SortableIterator::SORT_BY_TYPE;
506
507 return $this;
508 }
509
510 /**
511 * Sorts files and directories by the last accessed time.
512 *
513 * This is the time that the file was last accessed, read or written to.
514 *
515 * This can be slow as all the matching files and directories must be retrieved for comparison.
516 *
517 * @return $this
518 *
519 * @see SortableIterator
520 */
521 public function sortByAccessedTime(): static
522 {
523 $this->sort = SortableIterator::SORT_BY_ACCESSED_TIME;
524
525 return $this;
526 }
527
528 /**
529 * Reverses the sorting.
530 *
531 * @return $this
532 */
533 public function reverseSorting(): static
534 {
535 $this->reverseSorting = true;
536
537 return $this;
538 }
539
540 /**
541 * Sorts files and directories by the last inode changed time.
542 *
543 * This is the time that the inode information was last modified (permissions, owner, group or other metadata).
544 *
545 * On Windows, since inode is not available, changed time is actually the file creation time.
546 *
547 * This can be slow as all the matching files and directories must be retrieved for comparison.
548 *
549 * @return $this
550 *
551 * @see SortableIterator
552 */
553 public function sortByChangedTime(): static
554 {
555 $this->sort = SortableIterator::SORT_BY_CHANGED_TIME;
556
557 return $this;
558 }
559
560 /**
561 * Sorts files and directories by the last modified time.
562 *
563 * This is the last time the actual contents of the file were last modified.
564 *
565 * This can be slow as all the matching files and directories must be retrieved for comparison.
566 *
567 * @return $this
568 *
569 * @see SortableIterator
570 */
571 public function sortByModifiedTime(): static
572 {
573 $this->sort = SortableIterator::SORT_BY_MODIFIED_TIME;
574
575 return $this;
576 }
577
578 /**
579 * Filters the iterator with an anonymous function.
580 *
581 * The anonymous function receives a \SplFileInfo and must return false
582 * to remove files.
583 *
584 * @param \Closure(SplFileInfo): bool $closure
585 * @param bool $prune Whether to skip traversing directories further
586 *
587 * @return $this
588 *
589 * @see CustomFilterIterator
590 */
591 public function filter(\Closure $closure, bool $prune = false): static
592 {
593 $this->filters[] = $closure;
594
595 if ($prune) {
596 $this->pruneFilters[] = $closure;
597 }
598
599 return $this;
600 }
601
602 /**
603 * Forces the following of symlinks.
604 *
605 * @return $this
606 */
607 public function followLinks(): static
608 {
609 $this->followLinks = true;
610
611 return $this;
612 }
613
614 /**
615 * Tells finder to ignore unreadable directories.
616 *
617 * By default, scanning unreadable directories content throws an AccessDeniedException.
618 *
619 * @return $this
620 */
621 public function ignoreUnreadableDirs(bool $ignore = true): static
622 {
623 $this->ignoreUnreadableDirs = $ignore;
624
625 return $this;
626 }
627
628 /**
629 * Searches files and directories which match defined rules.
630 *
631 * @param string|string[] $dirs A directory path or an array of directories
632 *
633 * @return $this
634 *
635 * @throws DirectoryNotFoundException if one of the directories does not exist
636 */
637 public function in(string|array $dirs): static
638 {
639 $resolvedDirs = [];
640
641 foreach ((array) $dirs as $dir) {
642 if (is_dir($dir)) {
643 $resolvedDirs[] = [$this->normalizeDir($dir)];
644 } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? \GLOB_BRACE : 0) | \GLOB_ONLYDIR | \GLOB_NOSORT)) {
645 sort($glob);
646 $resolvedDirs[] = array_map($this->normalizeDir(...), $glob);
647 } else {
648 throw new DirectoryNotFoundException(\sprintf('The "%s" directory does not exist.', $dir));
649 }
650 }
651
652 $this->dirs = array_merge($this->dirs, ...$resolvedDirs);
653
654 return $this;
655 }
656
657 /**
658 * Returns an Iterator for the current Finder configuration.
659 *
660 * This method implements the IteratorAggregate interface.
661 *
662 * @return \Iterator<non-empty-string, SplFileInfo>
663 *
664 * @throws \LogicException if the in() method has not been called
665 */
666 public function getIterator(): \Iterator
667 {
668 if (!$this->dirs && !$this->iterators) {
669 throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
670 }
671
672 if (1 === \count($this->dirs) && !$this->iterators) {
673 $iterator = $this->searchInDirectory($this->dirs[0]);
674 } else {
675 $iterator = new \AppendIterator();
676 foreach ($this->dirs as $dir) {
677 $iterator->append(new \IteratorIterator(new LazyIterator(fn () => $this->searchInDirectory($dir))));
678 }
679
680 foreach ($this->iterators as $it) {
681 $iterator->append(new \IteratorIterator(new LazyIterator(static function () use ($it) {
682 foreach ($it as $file) {
683 if (!$file instanceof \SplFileInfo) {
684 $file = new \SplFileInfo($file);
685 }
686 $key = $file->getPathname();
687 if (!$file instanceof SplFileInfo) {
688 $file = new SplFileInfo($key, $file->getPath(), $key);
689 }
690
691 yield $key => $file;
692 }
693 })));
694 }
695 }
696
697 if ($this->sort || $this->reverseSorting) {
698 $iterator = (new SortableIterator($iterator, $this->sort, $this->reverseSorting))->getIterator();
699 }
700
701 return $iterator;
702 }
703
704 /**
705 * Appends an existing set of files/directories to the finder.
706 *
707 * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
708 *
709 * @param iterable<SplFileInfo|\SplFileInfo|string> $iterator
710 *
711 * @return $this
712 */
713 public function append(iterable $iterator): static
714 {
715 $this->iterators[] = $iterator;
716
717 return $this;
718 }
719
720 /**
721 * Check if any results were found.
722 */
723 public function hasResults(): bool
724 {
725 foreach ($this->getIterator() as $_) {
726 return true;
727 }
728
729 return false;
730 }
731
732 /**
733 * Counts all the results collected by the iterators.
734 */
735 public function count(): int
736 {
737 return iterator_count($this->getIterator());
738 }
739
740 private function searchInDirectory(string $dir): \Iterator
741 {
742 $exclude = $this->exclude;
743 $notPaths = $this->notPaths;
744
745 if ($this->pruneFilters) {
746 $exclude = array_merge($exclude, $this->pruneFilters);
747 }
748
749 if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
750 $exclude = array_merge($exclude, self::$vcsPatterns);
751 }
752
753 if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
754 $notPaths[] = '#(^|/)\..+(/|$)#';
755 }
756
757 $minDepth = 0;
758 $maxDepth = \PHP_INT_MAX;
759
760 foreach ($this->depths as $comparator) {
761 switch ($comparator->getOperator()) {
762 case '>':
763 $minDepth = $comparator->getTarget() + 1;
764 break;
765 case '>=':
766 $minDepth = $comparator->getTarget();
767 break;
768 case '<':
769 $maxDepth = $comparator->getTarget() - 1;
770 break;
771 case '<=':
772 $maxDepth = $comparator->getTarget();
773 break;
774 default:
775 $minDepth = $maxDepth = $comparator->getTarget();
776 }
777 }
778
779 $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
780
781 if ($this->followLinks) {
782 $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
783 }
784
785 $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
786
787 if ($exclude) {
788 $iterator = new ExcludeDirectoryFilterIterator($iterator, $exclude);
789 }
790
791 $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
792
793 if ($minDepth > 0 || $maxDepth < \PHP_INT_MAX) {
794 $iterator = new DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
795 }
796
797 if ($this->mode) {
798 $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
799 }
800
801 if ($this->names || $this->notNames) {
802 $iterator = new FilenameFilterIterator($iterator, $this->names, $this->notNames);
803 }
804
805 if ($this->contains || $this->notContains) {
806 $iterator = new FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
807 }
808
809 if ($this->sizes) {
810 $iterator = new SizeRangeFilterIterator($iterator, $this->sizes);
811 }
812
813 if ($this->dates) {
814 $iterator = new DateRangeFilterIterator($iterator, $this->dates);
815 }
816
817 if ($this->filters) {
818 $iterator = new CustomFilterIterator($iterator, $this->filters);
819 }
820
821 if ($this->paths || $notPaths) {
822 $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $notPaths);
823 }
824
825 if (static::IGNORE_VCS_IGNORED_FILES === (static::IGNORE_VCS_IGNORED_FILES & $this->ignore)) {
826 $iterator = new Iterator\VcsIgnoredFilterIterator($iterator, $dir);
827 }
828
829 return $iterator;
830 }
831
832 /**
833 * Normalizes given directory names by removing trailing slashes.
834 *
835 * Excluding: stream wrapper schemes such as ftp:// or s3://
836 */
837 private function normalizeDir(string $dir): string
838 {
839 if ('/' === $dir) {
840 return $dir;
841 }
842
843 $dir = rtrim($dir, '/'.\DIRECTORY_SEPARATOR);
844
845 if (preg_match('#^[a-zA-Z][a-zA-Z0-9.+-]*://#', $dir)) {
846 $dir .= '/';
847 }
848
849 return $dir;
850 }
851 }