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');
70 public function __construct()
72 $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
76 * Creates a new Finder.
80 public static function create()
86 * Registers a finder engine implementation.
88 * @param AdapterInterface $adapter An adapter instance
89 * @param int $priority Highest is selected first
93 * @deprecated since 2.8, to be removed in 3.0.
95 public function addAdapter(AdapterInterface $adapter, $priority = 0)
97 @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
99 $this->initDefaultAdapters();
101 $this->adapters[$adapter->getName()] = array(
102 'adapter' => $adapter,
103 'priority' => $priority,
107 return $this->sortAdapters();
111 * Sets the selected adapter to the best one according to the current platform the code is run on.
115 * @deprecated since 2.8, to be removed in 3.0.
117 public function useBestAdapter()
119 @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
121 $this->initDefaultAdapters();
123 $this->resetAdapterSelection();
125 return $this->sortAdapters();
129 * Selects the adapter to use.
131 * @param string $name
135 * @throws \InvalidArgumentException
137 * @deprecated since 2.8, to be removed in 3.0.
139 public function setAdapter($name)
141 @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
143 $this->initDefaultAdapters();
145 if (!isset($this->adapters[$name])) {
146 throw new \InvalidArgumentException(sprintf('Adapter "%s" does not exist.', $name));
149 $this->resetAdapterSelection();
150 $this->adapters[$name]['selected'] = true;
152 return $this->sortAdapters();
156 * Removes all adapters registered in the finder.
160 * @deprecated since 2.8, to be removed in 3.0.
162 public function removeAdapters()
164 @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
166 $this->adapters = array();
172 * Returns registered adapters ordered by priority without extra information.
174 * @return AdapterInterface[]
176 * @deprecated since 2.8, to be removed in 3.0.
178 public function getAdapters()
180 @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
182 $this->initDefaultAdapters();
184 return array_values(array_map(function (array $adapter) {
185 return $adapter['adapter'];
186 }, $this->adapters));
190 * Restricts the matching to directories only.
194 public function directories()
196 $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
202 * Restricts the matching to files only.
206 public function files()
208 $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
214 * Adds tests for the directory depth.
218 * $finder->depth('> 1') // the Finder will start matching at level 1.
219 * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point.
221 * @param string|int $level The depth level expression
225 * @see DepthRangeFilterIterator
226 * @see NumberComparator
228 public function depth($level)
230 $this->depths[] = new Comparator\NumberComparator($level);
236 * Adds tests for file dates (last modified).
238 * The date must be something that strtotime() is able to parse:
240 * $finder->date('since yesterday');
241 * $finder->date('until 2 days ago');
242 * $finder->date('> now - 2 hours');
243 * $finder->date('>= 2005-10-15');
245 * @param string $date A date range string
250 * @see DateRangeFilterIterator
251 * @see DateComparator
253 public function date($date)
255 $this->dates[] = new Comparator\DateComparator($date);
261 * Adds rules that files must match.
263 * You can use patterns (delimited with / sign), globs or simple strings.
265 * $finder->name('*.php')
266 * $finder->name('/\.php$/') // same as above
267 * $finder->name('test.php')
269 * @param string $pattern A pattern (a regexp, a glob, or a string)
273 * @see FilenameFilterIterator
275 public function name($pattern)
277 $this->names[] = $pattern;
283 * Adds rules that files must not match.
285 * @param string $pattern A pattern (a regexp, a glob, or a string)
289 * @see FilenameFilterIterator
291 public function notName($pattern)
293 $this->notNames[] = $pattern;
299 * Adds tests that file contents must match.
301 * Strings or PCRE patterns can be used:
303 * $finder->contains('Lorem ipsum')
304 * $finder->contains('/Lorem ipsum/i')
306 * @param string $pattern A pattern (string or regexp)
310 * @see FilecontentFilterIterator
312 public function contains($pattern)
314 $this->contains[] = $pattern;
320 * Adds tests that file contents must not match.
322 * Strings or PCRE patterns can be used:
324 * $finder->notContains('Lorem ipsum')
325 * $finder->notContains('/Lorem ipsum/i')
327 * @param string $pattern A pattern (string or regexp)
331 * @see FilecontentFilterIterator
333 public function notContains($pattern)
335 $this->notContains[] = $pattern;
341 * Adds rules that filenames must match.
343 * You can use patterns (delimited with / sign) or simple strings.
345 * $finder->path('some/special/dir')
346 * $finder->path('/some\/special\/dir/') // same as above
348 * Use only / as dirname separator.
350 * @param string $pattern A pattern (a regexp or a string)
354 * @see FilenameFilterIterator
356 public function path($pattern)
358 $this->paths[] = $pattern;
364 * Adds rules that filenames must not match.
366 * You can use patterns (delimited with / sign) or simple strings.
368 * $finder->notPath('some/special/dir')
369 * $finder->notPath('/some\/special\/dir/') // same as above
371 * Use only / as dirname separator.
373 * @param string $pattern A pattern (a regexp or a string)
377 * @see FilenameFilterIterator
379 public function notPath($pattern)
381 $this->notPaths[] = $pattern;
387 * Adds tests for file sizes.
389 * $finder->size('> 10K');
390 * $finder->size('<= 1Ki');
393 * @param string|int $size A size range string or an integer
397 * @see SizeRangeFilterIterator
398 * @see NumberComparator
400 public function size($size)
402 $this->sizes[] = new Comparator\NumberComparator($size);
408 * Excludes directories.
410 * @param string|array $dirs A directory path or an array of directories
414 * @see ExcludeDirectoryFilterIterator
416 public function exclude($dirs)
418 $this->exclude = array_merge($this->exclude, (array) $dirs);
424 * Excludes "hidden" directories and files (starting with a dot).
426 * This option is enabled by default.
428 * @param bool $ignoreDotFiles Whether to exclude "hidden" files or not
432 * @see ExcludeDirectoryFilterIterator
434 public function ignoreDotFiles($ignoreDotFiles)
436 if ($ignoreDotFiles) {
437 $this->ignore |= static::IGNORE_DOT_FILES;
439 $this->ignore &= ~static::IGNORE_DOT_FILES;
446 * Forces the finder to ignore version control directories.
448 * This option is enabled by default.
450 * @param bool $ignoreVCS Whether to exclude VCS files or not
454 * @see ExcludeDirectoryFilterIterator
456 public function ignoreVCS($ignoreVCS)
459 $this->ignore |= static::IGNORE_VCS_FILES;
461 $this->ignore &= ~static::IGNORE_VCS_FILES;
472 * @param string|string[] $pattern VCS patterns to ignore
474 public static function addVCSPattern($pattern)
476 foreach ((array) $pattern as $p) {
477 self::$vcsPatterns[] = $p;
480 self::$vcsPatterns = array_unique(self::$vcsPatterns);
484 * Sorts files and directories by an anonymous function.
486 * The anonymous function receives two \SplFileInfo instances to compare.
488 * This can be slow as all the matching files and directories must be retrieved for comparison.
492 * @see SortableIterator
494 public function sort(\Closure $closure)
496 $this->sort = $closure;
502 * Sorts files and directories by name.
504 * This can be slow as all the matching files and directories must be retrieved for comparison.
508 * @see SortableIterator
510 public function sortByName()
512 $this->sort = Iterator\SortableIterator::SORT_BY_NAME;
518 * Sorts files and directories by type (directories before files), then by name.
520 * This can be slow as all the matching files and directories must be retrieved for comparison.
524 * @see SortableIterator
526 public function sortByType()
528 $this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
534 * Sorts files and directories by the last accessed time.
536 * This is the time that the file was last accessed, read or written to.
538 * This can be slow as all the matching files and directories must be retrieved for comparison.
542 * @see SortableIterator
544 public function sortByAccessedTime()
546 $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
552 * Sorts files and directories by the last inode changed time.
554 * This is the time that the inode information was last modified (permissions, owner, group or other metadata).
556 * On Windows, since inode is not available, changed time is actually the file creation time.
558 * This can be slow as all the matching files and directories must be retrieved for comparison.
562 * @see SortableIterator
564 public function sortByChangedTime()
566 $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
572 * Sorts files and directories by the last modified time.
574 * This is the last time the actual contents of the file were last modified.
576 * This can be slow as all the matching files and directories must be retrieved for comparison.
580 * @see SortableIterator
582 public function sortByModifiedTime()
584 $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
590 * Filters the iterator with an anonymous function.
592 * The anonymous function receives a \SplFileInfo and must return false
597 * @see CustomFilterIterator
599 public function filter(\Closure $closure)
601 $this->filters[] = $closure;
607 * Forces the following of symlinks.
611 public function followLinks()
613 $this->followLinks = true;
619 * Tells finder to ignore unreadable directories.
621 * By default, scanning unreadable directories content throws an AccessDeniedException.
623 * @param bool $ignore
627 public function ignoreUnreadableDirs($ignore = true)
629 $this->ignoreUnreadableDirs = (bool) $ignore;
635 * Searches files and directories which match defined rules.
637 * @param string|array $dirs A directory path or an array of directories
641 * @throws \InvalidArgumentException if one of the directories does not exist
643 public function in($dirs)
645 $resolvedDirs = array();
647 foreach ((array) $dirs as $dir) {
649 $resolvedDirs[] = $dir;
650 } elseif ($glob = glob($dir, (defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) {
651 $resolvedDirs = array_merge($resolvedDirs, $glob);
653 throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
657 $this->dirs = array_merge($this->dirs, $resolvedDirs);
663 * Returns an Iterator for the current Finder configuration.
665 * This method implements the IteratorAggregate interface.
667 * @return \Iterator|SplFileInfo[] An iterator
669 * @throws \LogicException if the in() method has not been called
671 public function getIterator()
673 if (0 === count($this->dirs) && 0 === count($this->iterators)) {
674 throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
677 if (1 === count($this->dirs) && 0 === count($this->iterators)) {
678 return $this->searchInDirectory($this->dirs[0]);
681 $iterator = new \AppendIterator();
682 foreach ($this->dirs as $dir) {
683 $iterator->append($this->searchInDirectory($dir));
686 foreach ($this->iterators as $it) {
687 $iterator->append($it);
694 * Appends an existing set of files/directories to the finder.
696 * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
698 * @param mixed $iterator
702 * @throws \InvalidArgumentException when the given argument is not iterable
704 public function append($iterator)
706 if ($iterator instanceof \IteratorAggregate) {
707 $this->iterators[] = $iterator->getIterator();
708 } elseif ($iterator instanceof \Iterator) {
709 $this->iterators[] = $iterator;
710 } elseif ($iterator instanceof \Traversable || is_array($iterator)) {
711 $it = new \ArrayIterator();
712 foreach ($iterator as $file) {
713 $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
715 $this->iterators[] = $it;
717 throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
724 * Counts all the results collected by the iterators.
728 public function count()
730 return iterator_count($this->getIterator());
736 private function sortAdapters()
738 uasort($this->adapters, function (array $a, array $b) {
739 if ($a['selected'] || $b['selected']) {
740 return $a['selected'] ? -1 : 1;
743 return $a['priority'] > $b['priority'] ? -1 : 1;
754 private function searchInDirectory($dir)
756 if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
757 $this->exclude = array_merge($this->exclude, self::$vcsPatterns);
760 if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
761 $this->notPaths[] = '#(^|/)\..+(/|$)#';
764 if ($this->adapters) {
765 foreach ($this->adapters as $adapter) {
766 if ($adapter['adapter']->isSupported()) {
769 ->buildAdapter($adapter['adapter'])
770 ->searchInDirectory($dir);
771 } catch (ExceptionInterface $e) {
778 $maxDepth = PHP_INT_MAX;
780 foreach ($this->depths as $comparator) {
781 switch ($comparator->getOperator()) {
783 $minDepth = $comparator->getTarget() + 1;
786 $minDepth = $comparator->getTarget();
789 $maxDepth = $comparator->getTarget() - 1;
792 $maxDepth = $comparator->getTarget();
795 $minDepth = $maxDepth = $comparator->getTarget();
799 $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
801 if ($this->followLinks) {
802 $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
805 $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
807 if ($this->exclude) {
808 $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
811 $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
813 if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) {
814 $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
818 $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
821 if ($this->names || $this->notNames) {
822 $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
825 if ($this->contains || $this->notContains) {
826 $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
830 $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
834 $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
837 if ($this->filters) {
838 $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
841 if ($this->paths || $this->notPaths) {
842 $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
846 $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
847 $iterator = $iteratorAggregate->getIterator();
854 * @return AdapterInterface
856 private function buildAdapter(AdapterInterface $adapter)
859 ->setFollowLinks($this->followLinks)
860 ->setDepths($this->depths)
861 ->setMode($this->mode)
862 ->setExclude($this->exclude)
863 ->setNames($this->names)
864 ->setNotNames($this->notNames)
865 ->setContains($this->contains)
866 ->setNotContains($this->notContains)
867 ->setSizes($this->sizes)
868 ->setDates($this->dates)
869 ->setFilters($this->filters)
870 ->setSort($this->sort)
871 ->setPath($this->paths)
872 ->setNotPath($this->notPaths)
873 ->ignoreUnreadableDirs($this->ignoreUnreadableDirs);
877 * Unselects all adapters.
879 private function resetAdapterSelection()
881 $this->adapters = array_map(function (array $properties) {
882 $properties['selected'] = false;
888 private function initDefaultAdapters()
890 if (null === $this->adapters) {
891 $this->adapters = array();
893 ->addAdapter(new GnuFindAdapter())
894 ->addAdapter(new BsdFindAdapter())
895 ->addAdapter(new PhpAdapter(), -50)