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\Comparator\DateComparator;
15 use Symfony\Component\Finder\Comparator\NumberComparator;
16 use Symfony\Component\Finder\Iterator\CustomFilterIterator;
17 use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
18 use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
19 use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
20 use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
21 use Symfony\Component\Finder\Iterator\FilenameFilterIterator;
22 use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
23 use Symfony\Component\Finder\Iterator\SortableIterator;
26 * Finder allows to build rules to find files and directories.
28 * It is a thin wrapper around several specialized iterator classes.
30 * All rules may be invoked several times.
32 * All methods return the current Finder object to allow easy chaining:
34 * $finder = Finder::create()->files()->name('*.php')->in(__DIR__);
36 * @author Fabien Potencier <fabien@symfony.com>
38 class Finder implements \IteratorAggregate, \Countable
40 const IGNORE_VCS_FILES = 1;
41 const IGNORE_DOT_FILES = 2;
44 private $names = array();
45 private $notNames = array();
46 private $exclude = array();
47 private $filters = array();
48 private $depths = array();
49 private $sizes = array();
50 private $followLinks = false;
51 private $sort = false;
53 private $dirs = array();
54 private $dates = array();
55 private $iterators = array();
56 private $contains = array();
57 private $notContains = array();
58 private $paths = array();
59 private $notPaths = array();
60 private $ignoreUnreadableDirs = false;
62 private static $vcsPatterns = array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg');
64 public function __construct()
66 $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
70 * Creates a new Finder.
74 public static function create()
80 * Restricts the matching to directories only.
84 public function directories()
86 $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
92 * Restricts the matching to files only.
96 public function files()
98 $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
104 * Adds tests for the directory depth.
108 * $finder->depth('> 1') // the Finder will start matching at level 1.
109 * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point.
111 * @param string|int $level The depth level expression
115 * @see DepthRangeFilterIterator
116 * @see NumberComparator
118 public function depth($level)
120 $this->depths[] = new Comparator\NumberComparator($level);
126 * Adds tests for file dates (last modified).
128 * The date must be something that strtotime() is able to parse:
130 * $finder->date('since yesterday');
131 * $finder->date('until 2 days ago');
132 * $finder->date('> now - 2 hours');
133 * $finder->date('>= 2005-10-15');
135 * @param string $date A date range string
140 * @see DateRangeFilterIterator
141 * @see DateComparator
143 public function date($date)
145 $this->dates[] = new Comparator\DateComparator($date);
151 * Adds rules that files must match.
153 * You can use patterns (delimited with / sign), globs or simple strings.
155 * $finder->name('*.php')
156 * $finder->name('/\.php$/') // same as above
157 * $finder->name('test.php')
159 * @param string $pattern A pattern (a regexp, a glob, or a string)
163 * @see FilenameFilterIterator
165 public function name($pattern)
167 $this->names[] = $pattern;
173 * Adds rules that files must not match.
175 * @param string $pattern A pattern (a regexp, a glob, or a string)
179 * @see FilenameFilterIterator
181 public function notName($pattern)
183 $this->notNames[] = $pattern;
189 * Adds tests that file contents must match.
191 * Strings or PCRE patterns can be used:
193 * $finder->contains('Lorem ipsum')
194 * $finder->contains('/Lorem ipsum/i')
196 * @param string $pattern A pattern (string or regexp)
200 * @see FilecontentFilterIterator
202 public function contains($pattern)
204 $this->contains[] = $pattern;
210 * Adds tests that file contents must not match.
212 * Strings or PCRE patterns can be used:
214 * $finder->notContains('Lorem ipsum')
215 * $finder->notContains('/Lorem ipsum/i')
217 * @param string $pattern A pattern (string or regexp)
221 * @see FilecontentFilterIterator
223 public function notContains($pattern)
225 $this->notContains[] = $pattern;
231 * Adds rules that filenames must match.
233 * You can use patterns (delimited with / sign) or simple strings.
235 * $finder->path('some/special/dir')
236 * $finder->path('/some\/special\/dir/') // same as above
238 * Use only / as dirname separator.
240 * @param string $pattern A pattern (a regexp or a string)
244 * @see FilenameFilterIterator
246 public function path($pattern)
248 $this->paths[] = $pattern;
254 * Adds rules that filenames must not match.
256 * You can use patterns (delimited with / sign) or simple strings.
258 * $finder->notPath('some/special/dir')
259 * $finder->notPath('/some\/special\/dir/') // same as above
261 * Use only / as dirname separator.
263 * @param string $pattern A pattern (a regexp or a string)
267 * @see FilenameFilterIterator
269 public function notPath($pattern)
271 $this->notPaths[] = $pattern;
277 * Adds tests for file sizes.
279 * $finder->size('> 10K');
280 * $finder->size('<= 1Ki');
283 * @param string|int $size A size range string or an integer
287 * @see SizeRangeFilterIterator
288 * @see NumberComparator
290 public function size($size)
292 $this->sizes[] = new Comparator\NumberComparator($size);
298 * Excludes directories.
300 * Directories passed as argument must be relative to the ones defined with the `in()` method. For example:
302 * $finder->in(__DIR__)->exclude('ruby');
304 * @param string|array $dirs A directory path or an array of directories
308 * @see ExcludeDirectoryFilterIterator
310 public function exclude($dirs)
312 $this->exclude = array_merge($this->exclude, (array) $dirs);
318 * Excludes "hidden" directories and files (starting with a dot).
320 * This option is enabled by default.
322 * @param bool $ignoreDotFiles Whether to exclude "hidden" files or not
326 * @see ExcludeDirectoryFilterIterator
328 public function ignoreDotFiles($ignoreDotFiles)
330 if ($ignoreDotFiles) {
331 $this->ignore |= static::IGNORE_DOT_FILES;
333 $this->ignore &= ~static::IGNORE_DOT_FILES;
340 * Forces the finder to ignore version control directories.
342 * This option is enabled by default.
344 * @param bool $ignoreVCS Whether to exclude VCS files or not
348 * @see ExcludeDirectoryFilterIterator
350 public function ignoreVCS($ignoreVCS)
353 $this->ignore |= static::IGNORE_VCS_FILES;
355 $this->ignore &= ~static::IGNORE_VCS_FILES;
366 * @param string|string[] $pattern VCS patterns to ignore
368 public static function addVCSPattern($pattern)
370 foreach ((array) $pattern as $p) {
371 self::$vcsPatterns[] = $p;
374 self::$vcsPatterns = array_unique(self::$vcsPatterns);
378 * Sorts files and directories by an anonymous function.
380 * The anonymous function receives two \SplFileInfo instances to compare.
382 * This can be slow as all the matching files and directories must be retrieved for comparison.
386 * @see SortableIterator
388 public function sort(\Closure $closure)
390 $this->sort = $closure;
396 * Sorts files and directories by name.
398 * This can be slow as all the matching files and directories must be retrieved for comparison.
402 * @see SortableIterator
404 public function sortByName()
406 $this->sort = Iterator\SortableIterator::SORT_BY_NAME;
412 * Sorts files and directories by type (directories before files), then by name.
414 * This can be slow as all the matching files and directories must be retrieved for comparison.
418 * @see SortableIterator
420 public function sortByType()
422 $this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
428 * Sorts files and directories by the last accessed time.
430 * This is the time that the file was last accessed, read or written to.
432 * This can be slow as all the matching files and directories must be retrieved for comparison.
436 * @see SortableIterator
438 public function sortByAccessedTime()
440 $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
446 * Sorts files and directories by the last inode changed time.
448 * This is the time that the inode information was last modified (permissions, owner, group or other metadata).
450 * On Windows, since inode is not available, changed time is actually the file creation time.
452 * This can be slow as all the matching files and directories must be retrieved for comparison.
456 * @see SortableIterator
458 public function sortByChangedTime()
460 $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
466 * Sorts files and directories by the last modified time.
468 * This is the last time the actual contents of the file were last modified.
470 * This can be slow as all the matching files and directories must be retrieved for comparison.
474 * @see SortableIterator
476 public function sortByModifiedTime()
478 $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
484 * Filters the iterator with an anonymous function.
486 * The anonymous function receives a \SplFileInfo and must return false
491 * @see CustomFilterIterator
493 public function filter(\Closure $closure)
495 $this->filters[] = $closure;
501 * Forces the following of symlinks.
505 public function followLinks()
507 $this->followLinks = true;
513 * Tells finder to ignore unreadable directories.
515 * By default, scanning unreadable directories content throws an AccessDeniedException.
517 * @param bool $ignore
521 public function ignoreUnreadableDirs($ignore = true)
523 $this->ignoreUnreadableDirs = (bool) $ignore;
529 * Searches files and directories which match defined rules.
531 * @param string|array $dirs A directory path or an array of directories
535 * @throws \InvalidArgumentException if one of the directories does not exist
537 public function in($dirs)
539 $resolvedDirs = array();
541 foreach ((array) $dirs as $dir) {
543 $resolvedDirs[] = $this->normalizeDir($dir);
544 } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) {
545 $resolvedDirs = array_merge($resolvedDirs, array_map(array($this, 'normalizeDir'), $glob));
547 throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
551 $this->dirs = array_merge($this->dirs, $resolvedDirs);
557 * Returns an Iterator for the current Finder configuration.
559 * This method implements the IteratorAggregate interface.
561 * @return \Iterator|SplFileInfo[] An iterator
563 * @throws \LogicException if the in() method has not been called
565 public function getIterator()
567 if (0 === \count($this->dirs) && 0 === \count($this->iterators)) {
568 throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
571 if (1 === \count($this->dirs) && 0 === \count($this->iterators)) {
572 return $this->searchInDirectory($this->dirs[0]);
575 $iterator = new \AppendIterator();
576 foreach ($this->dirs as $dir) {
577 $iterator->append($this->searchInDirectory($dir));
580 foreach ($this->iterators as $it) {
581 $iterator->append($it);
588 * Appends an existing set of files/directories to the finder.
590 * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
592 * @param iterable $iterator
596 * @throws \InvalidArgumentException when the given argument is not iterable
598 public function append($iterator)
600 if ($iterator instanceof \IteratorAggregate) {
601 $this->iterators[] = $iterator->getIterator();
602 } elseif ($iterator instanceof \Iterator) {
603 $this->iterators[] = $iterator;
604 } elseif ($iterator instanceof \Traversable || \is_array($iterator)) {
605 $it = new \ArrayIterator();
606 foreach ($iterator as $file) {
607 $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
609 $this->iterators[] = $it;
611 throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
618 * Check if the any results were found.
622 public function hasResults()
624 foreach ($this->getIterator() as $_) {
632 * Counts all the results collected by the iterators.
636 public function count()
638 return iterator_count($this->getIterator());
646 private function searchInDirectory($dir)
648 if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
649 $this->exclude = array_merge($this->exclude, self::$vcsPatterns);
652 if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
653 $this->notPaths[] = '#(^|/)\..+(/|$)#';
657 $maxDepth = PHP_INT_MAX;
659 foreach ($this->depths as $comparator) {
660 switch ($comparator->getOperator()) {
662 $minDepth = $comparator->getTarget() + 1;
665 $minDepth = $comparator->getTarget();
668 $maxDepth = $comparator->getTarget() - 1;
671 $maxDepth = $comparator->getTarget();
674 $minDepth = $maxDepth = $comparator->getTarget();
678 $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
680 if ($this->followLinks) {
681 $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
684 $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
686 if ($this->exclude) {
687 $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
690 $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
692 if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) {
693 $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
697 $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
700 if ($this->names || $this->notNames) {
701 $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
704 if ($this->contains || $this->notContains) {
705 $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
709 $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
713 $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
716 if ($this->filters) {
717 $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
720 if ($this->paths || $this->notPaths) {
721 $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
725 $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
726 $iterator = $iteratorAggregate->getIterator();
733 * Normalizes given directory names by removing trailing slashes.
735 * Excluding: (s)ftp:// wrapper
741 private function normalizeDir($dir)
743 $dir = rtrim($dir, '/'.\DIRECTORY_SEPARATOR);
745 if (preg_match('#^s?ftp://#', $dir)) {