Finder.php 19 KB

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