4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Finder;
14 use Symfony\Component\Finder\Adapter\AdapterInterface;
15 use Symfony\Component\Finder\Adapter\GnuFindAdapter;
16 use Symfony\Component\Finder\Adapter\BsdFindAdapter;
17 use Symfony\Component\Finder\Adapter\PhpAdapter;
18 use Symfony\Component\Finder\Comparator\DateComparator;
19 use Symfony\Component\Finder\Comparator\NumberComparator;
20 use Symfony\Component\Finder\Exception\ExceptionInterface;
21 use Symfony\Component\Finder\Iterator\CustomFilterIterator;
22 use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
23 use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
24 use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
25 use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
26 use Symfony\Component\Finder\Iterator\FilenameFilterIterator;
27 use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
28 use Symfony\Component\Finder\Iterator\SortableIterator;
31 * Finder allows to build rules to find files and directories.
33 * It is a thin wrapper around several specialized iterator classes.
35 * All rules may be invoked several times.
37 * All methods return the current Finder object to allow easy chaining:
39 * $finder = Finder::create()->files()->name('*.php')->in(__DIR__);
41 * @author Fabien Potencier <fabien@symfony.com>
43 class Finder implements \IteratorAggregate, \Countable
45 const IGNORE_VCS_FILES = 1;
46 const IGNORE_DOT_FILES = 2;
49 private $names = array();
50 private $notNames = array();
51 private $exclude = array();
52 private $filters = array();
53 private $depths = array();
54 private $sizes = array();
55 private $followLinks = false;
56 private $sort = false;
58 private $dirs = array();
59 private $dates = array();
60 private $iterators = array();
61 private $contains = array();
62 private $notContains = array();
63 private $adapters = null;
64 private $paths = array();
65 private $notPaths = array();
66 private $ignoreUnreadableDirs = false;
68 private static $vcsPatterns = array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg');
73 public function __construct()
75 $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
79 * Creates a new Finder.
83 public static function create()
89 * Registers a finder engine implementation.
91 * @param AdapterInterface $adapter An adapter instance
92 * @param int $priority Highest is selected first
96 * @deprecated since 2.8, to be removed in 3.0.
98 public function addAdapter(AdapterInterface $adapter, $priority = 0)
100 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
102 $this->initDefaultAdapters();
104 $this->adapters[$adapter->getName()] = array(
105 'adapter' => $adapter,
106 'priority' => $priority,
110 return $this->sortAdapters();
114 * Sets the selected adapter to the best one according to the current platform the code is run on.
118 * @deprecated since 2.8, to be removed in 3.0.
120 public function useBestAdapter()
122 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
124 $this->initDefaultAdapters();
126 $this->resetAdapterSelection();
128 return $this->sortAdapters();
132 * Selects the adapter to use.
134 * @param string $name
138 * @throws \InvalidArgumentException
140 * @deprecated since 2.8, to be removed in 3.0.
142 public function setAdapter($name)
144 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
146 $this->initDefaultAdapters();
148 if (!isset($this->adapters[$name])) {
149 throw new \InvalidArgumentException(sprintf('Adapter "%s" does not exist.', $name));
152 $this->resetAdapterSelection();
153 $this->adapters[$name]['selected'] = true;
155 return $this->sortAdapters();
159 * Removes all adapters registered in the finder.
163 * @deprecated since 2.8, to be removed in 3.0.
165 public function removeAdapters()
167 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
169 $this->adapters = array();
175 * Returns registered adapters ordered by priority without extra information.
177 * @return AdapterInterface[]
179 * @deprecated since 2.8, to be removed in 3.0.
181 public function getAdapters()
183 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
185 $this->initDefaultAdapters();
187 return array_values(array_map(function (array $adapter) {
188 return $adapter['adapter'];
189 }, $this->adapters));
193 * Restricts the matching to directories only.
197 public function directories()
199 $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
205 * Restricts the matching to files only.
209 public function files()
211 $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
217 * Adds tests for the directory depth.
221 * $finder->depth('> 1') // the Finder will start matching at level 1.
222 * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point.
224 * @param string|int $level The depth level expression
228 * @see DepthRangeFilterIterator
229 * @see NumberComparator
231 public function depth($level)
233 $this->depths[] = new Comparator\NumberComparator($level);
239 * Adds tests for file dates (last modified).
241 * The date must be something that strtotime() is able to parse:
243 * $finder->date('since yesterday');
244 * $finder->date('until 2 days ago');
245 * $finder->date('> now - 2 hours');
246 * $finder->date('>= 2005-10-15');
248 * @param string $date A date range string
253 * @see DateRangeFilterIterator
254 * @see DateComparator
256 public function date($date)
258 $this->dates[] = new Comparator\DateComparator($date);
264 * Adds rules that files must match.
266 * You can use patterns (delimited with / sign), globs or simple strings.
268 * $finder->name('*.php')
269 * $finder->name('/\.php$/') // same as above
270 * $finder->name('test.php')
272 * @param string $pattern A pattern (a regexp, a glob, or a string)
276 * @see FilenameFilterIterator
278 public function name($pattern)
280 $this->names[] = $pattern;
286 * Adds rules that files must not match.
288 * @param string $pattern A pattern (a regexp, a glob, or a string)
292 * @see FilenameFilterIterator
294 public function notName($pattern)
296 $this->notNames[] = $pattern;
302 * Adds tests that file contents must match.
304 * Strings or PCRE patterns can be used:
306 * $finder->contains('Lorem ipsum')
307 * $finder->contains('/Lorem ipsum/i')
309 * @param string $pattern A pattern (string or regexp)
313 * @see FilecontentFilterIterator
315 public function contains($pattern)
317 $this->contains[] = $pattern;
323 * Adds tests that file contents must not match.
325 * Strings or PCRE patterns can be used:
327 * $finder->notContains('Lorem ipsum')
328 * $finder->notContains('/Lorem ipsum/i')
330 * @param string $pattern A pattern (string or regexp)
334 * @see FilecontentFilterIterator
336 public function notContains($pattern)
338 $this->notContains[] = $pattern;
344 * Adds rules that filenames must match.
346 * You can use patterns (delimited with / sign) or simple strings.
348 * $finder->path('some/special/dir')
349 * $finder->path('/some\/special\/dir/') // same as above
351 * Use only / as dirname separator.
353 * @param string $pattern A pattern (a regexp or a string)
357 * @see FilenameFilterIterator
359 public function path($pattern)
361 $this->paths[] = $pattern;
367 * Adds rules that filenames must not match.
369 * You can use patterns (delimited with / sign) or simple strings.
371 * $finder->notPath('some/special/dir')
372 * $finder->notPath('/some\/special\/dir/') // same as above
374 * Use only / as dirname separator.
376 * @param string $pattern A pattern (a regexp or a string)
380 * @see FilenameFilterIterator
382 public function notPath($pattern)
384 $this->notPaths[] = $pattern;
390 * Adds tests for file sizes.
392 * $finder->size('> 10K');
393 * $finder->size('<= 1Ki');
396 * @param string|int $size A size range string or an integer
400 * @see SizeRangeFilterIterator
401 * @see NumberComparator
403 public function size($size)
405 $this->sizes[] = new Comparator\NumberComparator($size);
411 * Excludes directories.
413 * @param string|array $dirs A directory path or an array of directories
417 * @see ExcludeDirectoryFilterIterator
419 public function exclude($dirs)
421 $this->exclude = array_merge($this->exclude, (array) $dirs);
427 * Excludes "hidden" directories and files (starting with a dot).
429 * @param bool $ignoreDotFiles Whether to exclude "hidden" files or not
433 * @see ExcludeDirectoryFilterIterator
435 public function ignoreDotFiles($ignoreDotFiles)
437 if ($ignoreDotFiles) {
438 $this->ignore |= static::IGNORE_DOT_FILES;
440 $this->ignore &= ~static::IGNORE_DOT_FILES;
447 * Forces the finder to ignore version control directories.
449 * @param bool $ignoreVCS Whether to exclude VCS files or not
453 * @see ExcludeDirectoryFilterIterator
455 public function ignoreVCS($ignoreVCS)
458 $this->ignore |= static::IGNORE_VCS_FILES;
460 $this->ignore &= ~static::IGNORE_VCS_FILES;
471 * @param string|string[] $pattern VCS patterns to ignore
473 public static function addVCSPattern($pattern)
475 foreach ((array) $pattern as $p) {
476 self::$vcsPatterns[] = $p;
479 self::$vcsPatterns = array_unique(self::$vcsPatterns);
483 * Sorts files and directories by an anonymous function.
485 * The anonymous function receives two \SplFileInfo instances to compare.
487 * This can be slow as all the matching files and directories must be retrieved for comparison.
489 * @param \Closure $closure An anonymous function
493 * @see SortableIterator
495 public function sort(\Closure $closure)
497 $this->sort = $closure;
503 * Sorts files and directories by name.
505 * This can be slow as all the matching files and directories must be retrieved for comparison.
509 * @see SortableIterator
511 public function sortByName()
513 $this->sort = Iterator\SortableIterator::SORT_BY_NAME;
519 * Sorts files and directories by type (directories before files), then by name.
521 * This can be slow as all the matching files and directories must be retrieved for comparison.
525 * @see SortableIterator
527 public function sortByType()
529 $this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
535 * Sorts files and directories by the last accessed time.
537 * This is the time that the file was last accessed, read or written to.
539 * This can be slow as all the matching files and directories must be retrieved for comparison.
543 * @see SortableIterator
545 public function sortByAccessedTime()
547 $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
553 * Sorts files and directories by the last inode changed time.
555 * This is the time that the inode information was last modified (permissions, owner, group or other metadata).
557 * On Windows, since inode is not available, changed time is actually the file creation time.
559 * This can be slow as all the matching files and directories must be retrieved for comparison.
563 * @see SortableIterator
565 public function sortByChangedTime()
567 $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
573 * Sorts files and directories by the last modified time.
575 * This is the last time the actual contents of the file were last modified.
577 * This can be slow as all the matching files and directories must be retrieved for comparison.
581 * @see SortableIterator
583 public function sortByModifiedTime()
585 $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
591 * Filters the iterator with an anonymous function.
593 * The anonymous function receives a \SplFileInfo and must return false
596 * @param \Closure $closure An anonymous function
600 * @see CustomFilterIterator
602 public function filter(\Closure $closure)
604 $this->filters[] = $closure;
610 * Forces the following of symlinks.
614 public function followLinks()
616 $this->followLinks = true;
622 * Tells finder to ignore unreadable directories.
624 * By default, scanning unreadable directories content throws an AccessDeniedException.
626 * @param bool $ignore
630 public function ignoreUnreadableDirs($ignore = true)
632 $this->ignoreUnreadableDirs = (bool) $ignore;
638 * Searches files and directories which match defined rules.
640 * @param string|array $dirs A directory path or an array of directories
644 * @throws \InvalidArgumentException if one of the directories does not exist
646 public function in($dirs)
648 $resolvedDirs = array();
650 foreach ((array) $dirs as $dir) {
652 $resolvedDirs[] = $dir;
653 } elseif ($glob = glob($dir, (defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) {
654 $resolvedDirs = array_merge($resolvedDirs, $glob);
656 throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
660 $this->dirs = array_merge($this->dirs, $resolvedDirs);
666 * Returns an Iterator for the current Finder configuration.
668 * This method implements the IteratorAggregate interface.
670 * @return \Iterator|SplFileInfo[] An iterator
672 * @throws \LogicException if the in() method has not been called
674 public function getIterator()
676 if (0 === count($this->dirs) && 0 === count($this->iterators)) {
677 throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
680 if (1 === count($this->dirs) && 0 === count($this->iterators)) {
681 return $this->searchInDirectory($this->dirs[0]);
684 $iterator = new \AppendIterator();
685 foreach ($this->dirs as $dir) {
686 $iterator->append($this->searchInDirectory($dir));
689 foreach ($this->iterators as $it) {
690 $iterator->append($it);
697 * Appends an existing set of files/directories to the finder.
699 * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
701 * @param mixed $iterator
705 * @throws \InvalidArgumentException When the given argument is not iterable.
707 public function append($iterator)
709 if ($iterator instanceof \IteratorAggregate) {
710 $this->iterators[] = $iterator->getIterator();
711 } elseif ($iterator instanceof \Iterator) {
712 $this->iterators[] = $iterator;
713 } elseif ($iterator instanceof \Traversable || is_array($iterator)) {
714 $it = new \ArrayIterator();
715 foreach ($iterator as $file) {
716 $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
718 $this->iterators[] = $it;
720 throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
727 * Counts all the results collected by the iterators.
731 public function count()
733 return iterator_count($this->getIterator());
739 private function sortAdapters()
741 uasort($this->adapters, function (array $a, array $b) {
742 if ($a['selected'] || $b['selected']) {
743 return $a['selected'] ? -1 : 1;
746 return $a['priority'] > $b['priority'] ? -1 : 1;
757 private function searchInDirectory($dir)
759 if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
760 $this->exclude = array_merge($this->exclude, self::$vcsPatterns);
763 if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
764 $this->notPaths[] = '#(^|/)\..+(/|$)#';
767 if ($this->adapters) {
768 foreach ($this->adapters as $adapter) {
769 if ($adapter['adapter']->isSupported()) {
772 ->buildAdapter($adapter['adapter'])
773 ->searchInDirectory($dir);
774 } catch (ExceptionInterface $e) {
781 $maxDepth = PHP_INT_MAX;
783 foreach ($this->depths as $comparator) {
784 switch ($comparator->getOperator()) {
786 $minDepth = $comparator->getTarget() + 1;
789 $minDepth = $comparator->getTarget();
792 $maxDepth = $comparator->getTarget() - 1;
795 $maxDepth = $comparator->getTarget();
798 $minDepth = $maxDepth = $comparator->getTarget();
802 $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
804 if ($this->followLinks) {
805 $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
808 $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
810 if ($this->exclude) {
811 $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
814 $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
816 if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) {
817 $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
821 $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
824 if ($this->names || $this->notNames) {
825 $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
828 if ($this->contains || $this->notContains) {
829 $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
833 $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
837 $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
840 if ($this->filters) {
841 $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
844 if ($this->paths || $this->notPaths) {
845 $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
849 $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
850 $iterator = $iteratorAggregate->getIterator();
857 * @param AdapterInterface $adapter
859 * @return AdapterInterface
861 private function buildAdapter(AdapterInterface $adapter)
864 ->setFollowLinks($this->followLinks)
865 ->setDepths($this->depths)
866 ->setMode($this->mode)
867 ->setExclude($this->exclude)
868 ->setNames($this->names)
869 ->setNotNames($this->notNames)
870 ->setContains($this->contains)
871 ->setNotContains($this->notContains)
872 ->setSizes($this->sizes)
873 ->setDates($this->dates)
874 ->setFilters($this->filters)
875 ->setSort($this->sort)
876 ->setPath($this->paths)
877 ->setNotPath($this->notPaths)
878 ->ignoreUnreadableDirs($this->ignoreUnreadableDirs);
882 * Unselects all adapters.
884 private function resetAdapterSelection()
886 $this->adapters = array_map(function (array $properties) {
887 $properties['selected'] = false;
893 private function initDefaultAdapters()
895 if (null === $this->adapters) {
896 $this->adapters = array();
898 ->addAdapter(new GnuFindAdapter())
899 ->addAdapter(new BsdFindAdapter())
900 ->addAdapter(new PhpAdapter(), -50)