Finder.php 19KB

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