Finder.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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;
  11. use Symfony\Component\Finder\Comparator\DateComparator;
  12. use Symfony\Component\Finder\Comparator\NumberComparator;
  13. use Symfony\Component\Finder\Iterator\CustomFilterIterator;
  14. use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
  15. use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
  16. use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
  17. use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
  18. use Symfony\Component\Finder\Iterator\FilenameFilterIterator;
  19. use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
  20. use Symfony\Component\Finder\Iterator\SortableIterator;
  21. /**
  22. * Finder allows to build rules to find files and directories.
  23. *
  24. * It is a thin wrapper around several specialized iterator classes.
  25. *
  26. * All rules may be invoked several times.
  27. *
  28. * All methods return the current Finder object to allow easy chaining:
  29. *
  30. * $finder = Finder::create()->files()->name('*.php')->in(__DIR__);
  31. *
  32. * @author Fabien Potencier <fabien@symfony.com>
  33. */
  34. class Finder implements \IteratorAggregate, \Countable
  35. {
  36. const IGNORE_VCS_FILES = 1;
  37. const IGNORE_DOT_FILES = 2;
  38. private $mode = 0;
  39. private $names = array();
  40. private $notNames = array();
  41. private $exclude = array();
  42. private $filters = array();
  43. private $depths = array();
  44. private $sizes = array();
  45. private $followLinks = false;
  46. private $sort = false;
  47. private $ignore = 0;
  48. private $dirs = array();
  49. private $dates = array();
  50. private $iterators = array();
  51. private $contains = array();
  52. private $notContains = array();
  53. private $paths = array();
  54. private $notPaths = array();
  55. private $ignoreUnreadableDirs = false;
  56. private static $vcsPatterns = array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg');
  57. public function __construct()
  58. {
  59. $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
  60. }
  61. /**
  62. * Creates a new Finder.
  63. *
  64. * @return static
  65. */
  66. public static function create()
  67. {
  68. return new static();
  69. }
  70. /**
  71. * Restricts the matching to directories only.
  72. *
  73. * @return $this
  74. */
  75. public function directories()
  76. {
  77. $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
  78. return $this;
  79. }
  80. /**
  81. * Restricts the matching to files only.
  82. *
  83. * @return $this
  84. */
  85. public function files()
  86. {
  87. $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
  88. return $this;
  89. }
  90. /**
  91. * Adds tests for the directory depth.
  92. *
  93. * Usage:
  94. *
  95. * $finder->depth('> 1') // the Finder will start matching at level 1.
  96. * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point.
  97. * $finder->depth(['>= 1', '< 3'])
  98. *
  99. * @param string|int|string[]|int[] $levels The depth level expression or an array of depth levels
  100. *
  101. * @return $this
  102. *
  103. * @see DepthRangeFilterIterator
  104. * @see NumberComparator
  105. */
  106. public function depth($levels)
  107. {
  108. foreach ((array) $levels as $level) {
  109. $this->depths[] = new Comparator\NumberComparator($level);
  110. }
  111. return $this;
  112. }
  113. /**
  114. * Adds tests for file dates (last modified).
  115. *
  116. * The date must be something that strtotime() is able to parse:
  117. *
  118. * $finder->date('since yesterday');
  119. * $finder->date('until 2 days ago');
  120. * $finder->date('> now - 2 hours');
  121. * $finder->date('>= 2005-10-15');
  122. * $finder->date(['>= 2005-10-15', '<= 2006-05-27']);
  123. *
  124. * @param string|string[] $dates A date range string or an array of date ranges
  125. *
  126. * @return $this
  127. *
  128. * @see strtotime
  129. * @see DateRangeFilterIterator
  130. * @see DateComparator
  131. */
  132. public function date($dates)
  133. {
  134. foreach ((array) $dates as $date) {
  135. $this->dates[] = new Comparator\DateComparator($date);
  136. }
  137. return $this;
  138. }
  139. /**
  140. * Adds rules that files must match.
  141. *
  142. * You can use patterns (delimited with / sign), globs or simple strings.
  143. *
  144. * $finder->name('*.php')
  145. * $finder->name('/\.php$/') // same as above
  146. * $finder->name('test.php')
  147. * $finder->name(['test.py', 'test.php'])
  148. *
  149. * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns
  150. *
  151. * @return $this
  152. *
  153. * @see FilenameFilterIterator
  154. */
  155. public function name($patterns)
  156. {
  157. $this->names = \array_merge($this->names, (array) $patterns);
  158. return $this;
  159. }
  160. /**
  161. * Adds rules that files must not match.
  162. *
  163. * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns
  164. *
  165. * @return $this
  166. *
  167. * @see FilenameFilterIterator
  168. */
  169. public function notName($patterns)
  170. {
  171. $this->notNames = \array_merge($this->notNames, (array) $patterns);
  172. return $this;
  173. }
  174. /**
  175. * Adds tests that file contents must match.
  176. *
  177. * Strings or PCRE patterns can be used:
  178. *
  179. * $finder->contains('Lorem ipsum')
  180. * $finder->contains('/Lorem ipsum/i')
  181. * $finder->contains(['dolor', '/ipsum/i'])
  182. *
  183. * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns
  184. *
  185. * @return $this
  186. *
  187. * @see FilecontentFilterIterator
  188. */
  189. public function contains($patterns)
  190. {
  191. $this->contains = \array_merge($this->contains, (array) $patterns);
  192. return $this;
  193. }
  194. /**
  195. * Adds tests that file contents must not match.
  196. *
  197. * Strings or PCRE patterns can be used:
  198. *
  199. * $finder->notContains('Lorem ipsum')
  200. * $finder->notContains('/Lorem ipsum/i')
  201. * $finder->notContains(['lorem', '/dolor/i'])
  202. *
  203. * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns
  204. *
  205. * @return $this
  206. *
  207. * @see FilecontentFilterIterator
  208. */
  209. public function notContains($patterns)
  210. {
  211. $this->notContains = \array_merge($this->notContains, (array) $patterns);
  212. return $this;
  213. }
  214. /**
  215. * Adds rules that filenames must match.
  216. *
  217. * You can use patterns (delimited with / sign) or simple strings.
  218. *
  219. * $finder->path('some/special/dir')
  220. * $finder->path('/some\/special\/dir/') // same as above
  221. * $finder->path(['some dir', 'another/dir'])
  222. *
  223. * Use only / as dirname separator.
  224. *
  225. * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns
  226. *
  227. * @return $this
  228. *
  229. * @see FilenameFilterIterator
  230. */
  231. public function path($patterns)
  232. {
  233. $this->paths = \array_merge($this->paths, (array) $patterns);
  234. return $this;
  235. }
  236. /**
  237. * Adds rules that filenames must not match.
  238. *
  239. * You can use patterns (delimited with / sign) or simple strings.
  240. *
  241. * $finder->notPath('some/special/dir')
  242. * $finder->notPath('/some\/special\/dir/') // same as above
  243. * $finder->notPath(['some/file.txt', 'another/file.log'])
  244. *
  245. * Use only / as dirname separator.
  246. *
  247. * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns
  248. *
  249. * @return $this
  250. *
  251. * @see FilenameFilterIterator
  252. */
  253. public function notPath($patterns)
  254. {
  255. $this->notPaths = \array_merge($this->notPaths, (array) $patterns);
  256. return $this;
  257. }
  258. /**
  259. * Adds tests for file sizes.
  260. *
  261. * $finder->size('> 10K');
  262. * $finder->size('<= 1Ki');
  263. * $finder->size(4);
  264. * $finder->size(['> 10K', '< 20K'])
  265. *
  266. * @param string|int|string[]|int[] $sizes A size range string or an integer or an array of size ranges
  267. *
  268. * @return $this
  269. *
  270. * @see SizeRangeFilterIterator
  271. * @see NumberComparator
  272. */
  273. public function size($sizes)
  274. {
  275. foreach ((array) $sizes as $size) {
  276. $this->sizes[] = new Comparator\NumberComparator($size);
  277. }
  278. return $this;
  279. }
  280. /**
  281. * Excludes directories.
  282. *
  283. * Directories passed as argument must be relative to the ones defined with the `in()` method. For example:
  284. *
  285. * $finder->in(__DIR__)->exclude('ruby');
  286. *
  287. * @param string|array $dirs A directory path or an array of directories
  288. *
  289. * @return $this
  290. *
  291. * @see ExcludeDirectoryFilterIterator
  292. */
  293. public function exclude($dirs)
  294. {
  295. $this->exclude = array_merge($this->exclude, (array) $dirs);
  296. return $this;
  297. }
  298. /**
  299. * Excludes "hidden" directories and files (starting with a dot).
  300. *
  301. * This option is enabled by default.
  302. *
  303. * @param bool $ignoreDotFiles Whether to exclude "hidden" files or not
  304. *
  305. * @return $this
  306. *
  307. * @see ExcludeDirectoryFilterIterator
  308. */
  309. public function ignoreDotFiles($ignoreDotFiles)
  310. {
  311. if ($ignoreDotFiles) {
  312. $this->ignore |= static::IGNORE_DOT_FILES;
  313. } else {
  314. $this->ignore &= ~static::IGNORE_DOT_FILES;
  315. }
  316. return $this;
  317. }
  318. /**
  319. * Forces the finder to ignore version control directories.
  320. *
  321. * This option is enabled by default.
  322. *
  323. * @param bool $ignoreVCS Whether to exclude VCS files or not
  324. *
  325. * @return $this
  326. *
  327. * @see ExcludeDirectoryFilterIterator
  328. */
  329. public function ignoreVCS($ignoreVCS)
  330. {
  331. if ($ignoreVCS) {
  332. $this->ignore |= static::IGNORE_VCS_FILES;
  333. } else {
  334. $this->ignore &= ~static::IGNORE_VCS_FILES;
  335. }
  336. return $this;
  337. }
  338. /**
  339. * Adds VCS patterns.
  340. *
  341. * @see ignoreVCS()
  342. *
  343. * @param string|string[] $pattern VCS patterns to ignore
  344. */
  345. public static function addVCSPattern($pattern)
  346. {
  347. foreach ((array) $pattern as $p) {
  348. self::$vcsPatterns[] = $p;
  349. }
  350. self::$vcsPatterns = array_unique(self::$vcsPatterns);
  351. }
  352. /**
  353. * Sorts files and directories by an anonymous function.
  354. *
  355. * The anonymous function receives two \SplFileInfo instances to compare.
  356. *
  357. * This can be slow as all the matching files and directories must be retrieved for comparison.
  358. *
  359. * @return $this
  360. *
  361. * @see SortableIterator
  362. */
  363. public function sort(\Closure $closure)
  364. {
  365. $this->sort = $closure;
  366. return $this;
  367. }
  368. /**
  369. * Sorts files and directories by name.
  370. *
  371. * This can be slow as all the matching files and directories must be retrieved for comparison.
  372. *
  373. * @param bool $useNaturalSort Whether to use natural sort or not, disabled by default
  374. *
  375. * @return $this
  376. *
  377. * @see SortableIterator
  378. */
  379. public function sortByName(/* bool $useNaturalSort = false */)
  380. {
  381. $useNaturalSort = 0 < func_num_args() && func_get_arg(0);
  382. $this->sort = $useNaturalSort ? Iterator\SortableIterator::SORT_BY_NAME_NATURAL : Iterator\SortableIterator::SORT_BY_NAME;
  383. return $this;
  384. }
  385. /**
  386. * Sorts files and directories by type (directories before files), then by name.
  387. *
  388. * This can be slow as all the matching files and directories must be retrieved for comparison.
  389. *
  390. * @return $this
  391. *
  392. * @see SortableIterator
  393. */
  394. public function sortByType()
  395. {
  396. $this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
  397. return $this;
  398. }
  399. /**
  400. * Sorts files and directories by the last accessed time.
  401. *
  402. * This is the time that the file was last accessed, read or written to.
  403. *
  404. * This can be slow as all the matching files and directories must be retrieved for comparison.
  405. *
  406. * @return $this
  407. *
  408. * @see SortableIterator
  409. */
  410. public function sortByAccessedTime()
  411. {
  412. $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
  413. return $this;
  414. }
  415. /**
  416. * Sorts files and directories by the last inode changed time.
  417. *
  418. * This is the time that the inode information was last modified (permissions, owner, group or other metadata).
  419. *
  420. * On Windows, since inode is not available, changed time is actually the file creation time.
  421. *
  422. * This can be slow as all the matching files and directories must be retrieved for comparison.
  423. *
  424. * @return $this
  425. *
  426. * @see SortableIterator
  427. */
  428. public function sortByChangedTime()
  429. {
  430. $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
  431. return $this;
  432. }
  433. /**
  434. * Sorts files and directories by the last modified time.
  435. *
  436. * This is the last time the actual contents of the file were last modified.
  437. *
  438. * This can be slow as all the matching files and directories must be retrieved for comparison.
  439. *
  440. * @return $this
  441. *
  442. * @see SortableIterator
  443. */
  444. public function sortByModifiedTime()
  445. {
  446. $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
  447. return $this;
  448. }
  449. /**
  450. * Filters the iterator with an anonymous function.
  451. *
  452. * The anonymous function receives a \SplFileInfo and must return false
  453. * to remove files.
  454. *
  455. * @return $this
  456. *
  457. * @see CustomFilterIterator
  458. */
  459. public function filter(\Closure $closure)
  460. {
  461. $this->filters[] = $closure;
  462. return $this;
  463. }
  464. /**
  465. * Forces the following of symlinks.
  466. *
  467. * @return $this
  468. */
  469. public function followLinks()
  470. {
  471. $this->followLinks = true;
  472. return $this;
  473. }
  474. /**
  475. * Tells finder to ignore unreadable directories.
  476. *
  477. * By default, scanning unreadable directories content throws an AccessDeniedException.
  478. *
  479. * @param bool $ignore
  480. *
  481. * @return $this
  482. */
  483. public function ignoreUnreadableDirs($ignore = true)
  484. {
  485. $this->ignoreUnreadableDirs = (bool) $ignore;
  486. return $this;
  487. }
  488. /**
  489. * Searches files and directories which match defined rules.
  490. *
  491. * @param string|array $dirs A directory path or an array of directories
  492. *
  493. * @return $this
  494. *
  495. * @throws \InvalidArgumentException if one of the directories does not exist
  496. */
  497. public function in($dirs)
  498. {
  499. $resolvedDirs = array();
  500. foreach ((array) $dirs as $dir) {
  501. if (is_dir($dir)) {
  502. $resolvedDirs[] = $this->normalizeDir($dir);
  503. } elseif ($glob = glob($dir, (defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) {
  504. $resolvedDirs = array_merge($resolvedDirs, array_map(array($this, 'normalizeDir'), $glob));
  505. } else {
  506. throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
  507. }
  508. }
  509. $this->dirs = array_merge($this->dirs, $resolvedDirs);
  510. return $this;
  511. }
  512. /**
  513. * Returns an Iterator for the current Finder configuration.
  514. *
  515. * This method implements the IteratorAggregate interface.
  516. *
  517. * @return \Iterator|SplFileInfo[] An iterator
  518. *
  519. * @throws \LogicException if the in() method has not been called
  520. */
  521. public function getIterator()
  522. {
  523. if (0 === count($this->dirs) && 0 === count($this->iterators)) {
  524. throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
  525. }
  526. if (1 === count($this->dirs) && 0 === count($this->iterators)) {
  527. return $this->searchInDirectory($this->dirs[0]);
  528. }
  529. $iterator = new \AppendIterator();
  530. foreach ($this->dirs as $dir) {
  531. $iterator->append($this->searchInDirectory($dir));
  532. }
  533. foreach ($this->iterators as $it) {
  534. $iterator->append($it);
  535. }
  536. return $iterator;
  537. }
  538. /**
  539. * Appends an existing set of files/directories to the finder.
  540. *
  541. * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
  542. *
  543. * @param mixed $iterator
  544. *
  545. * @return $this
  546. *
  547. * @throws \InvalidArgumentException when the given argument is not iterable
  548. */
  549. public function append($iterator)
  550. {
  551. if ($iterator instanceof \IteratorAggregate) {
  552. $this->iterators[] = $iterator->getIterator();
  553. } elseif ($iterator instanceof \Iterator) {
  554. $this->iterators[] = $iterator;
  555. } elseif ($iterator instanceof \Traversable || is_array($iterator)) {
  556. $it = new \ArrayIterator();
  557. foreach ($iterator as $file) {
  558. $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
  559. }
  560. $this->iterators[] = $it;
  561. } else {
  562. throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
  563. }
  564. return $this;
  565. }
  566. /**
  567. * Check if the any results were found.
  568. *
  569. * @return bool
  570. */
  571. public function hasResults()
  572. {
  573. foreach ($this->getIterator() as $_) {
  574. return true;
  575. }
  576. return false;
  577. }
  578. /**
  579. * Counts all the results collected by the iterators.
  580. *
  581. * @return int
  582. */
  583. public function count()
  584. {
  585. return iterator_count($this->getIterator());
  586. }
  587. private function searchInDirectory(string $dir): \Iterator
  588. {
  589. if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
  590. $this->exclude = array_merge($this->exclude, self::$vcsPatterns);
  591. }
  592. if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
  593. $this->notPaths[] = '#(^|/)\..+(/|$)#';
  594. }
  595. $minDepth = 0;
  596. $maxDepth = PHP_INT_MAX;
  597. foreach ($this->depths as $comparator) {
  598. switch ($comparator->getOperator()) {
  599. case '>':
  600. $minDepth = $comparator->getTarget() + 1;
  601. break;
  602. case '>=':
  603. $minDepth = $comparator->getTarget();
  604. break;
  605. case '<':
  606. $maxDepth = $comparator->getTarget() - 1;
  607. break;
  608. case '<=':
  609. $maxDepth = $comparator->getTarget();
  610. break;
  611. default:
  612. $minDepth = $maxDepth = $comparator->getTarget();
  613. }
  614. }
  615. $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
  616. if ($this->followLinks) {
  617. $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
  618. }
  619. $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
  620. if ($this->exclude) {
  621. $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
  622. }
  623. $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
  624. if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) {
  625. $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
  626. }
  627. if ($this->mode) {
  628. $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
  629. }
  630. if ($this->names || $this->notNames) {
  631. $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
  632. }
  633. if ($this->contains || $this->notContains) {
  634. $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
  635. }
  636. if ($this->sizes) {
  637. $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
  638. }
  639. if ($this->dates) {
  640. $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
  641. }
  642. if ($this->filters) {
  643. $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
  644. }
  645. if ($this->paths || $this->notPaths) {
  646. $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
  647. }
  648. if ($this->sort) {
  649. $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
  650. $iterator = $iteratorAggregate->getIterator();
  651. }
  652. return $iterator;
  653. }
  654. /**
  655. * Normalizes given directory names by removing trailing slashes.
  656. *
  657. * @param string $dir
  658. *
  659. * @return string
  660. */
  661. private function normalizeDir($dir)
  662. {
  663. return rtrim($dir, '/'.\DIRECTORY_SEPARATOR);
  664. }
  665. }