菜谱项目

Finder.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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. * @param string|array $dirs A directory path or an array of directories
  270. *
  271. * @return $this
  272. *
  273. * @see ExcludeDirectoryFilterIterator
  274. */
  275. public function exclude($dirs)
  276. {
  277. $this->exclude = array_merge($this->exclude, (array) $dirs);
  278. return $this;
  279. }
  280. /**
  281. * Excludes "hidden" directories and files (starting with a dot).
  282. *
  283. * @param bool $ignoreDotFiles Whether to exclude "hidden" files or not
  284. *
  285. * @return $this
  286. *
  287. * @see ExcludeDirectoryFilterIterator
  288. */
  289. public function ignoreDotFiles($ignoreDotFiles)
  290. {
  291. if ($ignoreDotFiles) {
  292. $this->ignore |= static::IGNORE_DOT_FILES;
  293. } else {
  294. $this->ignore &= ~static::IGNORE_DOT_FILES;
  295. }
  296. return $this;
  297. }
  298. /**
  299. * Forces the finder to ignore version control directories.
  300. *
  301. * @param bool $ignoreVCS Whether to exclude VCS files or not
  302. *
  303. * @return $this
  304. *
  305. * @see ExcludeDirectoryFilterIterator
  306. */
  307. public function ignoreVCS($ignoreVCS)
  308. {
  309. if ($ignoreVCS) {
  310. $this->ignore |= static::IGNORE_VCS_FILES;
  311. } else {
  312. $this->ignore &= ~static::IGNORE_VCS_FILES;
  313. }
  314. return $this;
  315. }
  316. /**
  317. * Adds VCS patterns.
  318. *
  319. * @see ignoreVCS()
  320. *
  321. * @param string|string[] $pattern VCS patterns to ignore
  322. */
  323. public static function addVCSPattern($pattern)
  324. {
  325. foreach ((array) $pattern as $p) {
  326. self::$vcsPatterns[] = $p;
  327. }
  328. self::$vcsPatterns = array_unique(self::$vcsPatterns);
  329. }
  330. /**
  331. * Sorts files and directories by an anonymous function.
  332. *
  333. * The anonymous function receives two \SplFileInfo instances to compare.
  334. *
  335. * This can be slow as all the matching files and directories must be retrieved for comparison.
  336. *
  337. * @return $this
  338. *
  339. * @see SortableIterator
  340. */
  341. public function sort(\Closure $closure)
  342. {
  343. $this->sort = $closure;
  344. return $this;
  345. }
  346. /**
  347. * Sorts files and directories by name.
  348. *
  349. * This can be slow as all the matching files and directories must be retrieved for comparison.
  350. *
  351. * @return $this
  352. *
  353. * @see SortableIterator
  354. */
  355. public function sortByName()
  356. {
  357. $this->sort = Iterator\SortableIterator::SORT_BY_NAME;
  358. return $this;
  359. }
  360. /**
  361. * Sorts files and directories by type (directories before files), then by name.
  362. *
  363. * This can be slow as all the matching files and directories must be retrieved for comparison.
  364. *
  365. * @return $this
  366. *
  367. * @see SortableIterator
  368. */
  369. public function sortByType()
  370. {
  371. $this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
  372. return $this;
  373. }
  374. /**
  375. * Sorts files and directories by the last accessed time.
  376. *
  377. * This is the time that the file was last accessed, read or written to.
  378. *
  379. * This can be slow as all the matching files and directories must be retrieved for comparison.
  380. *
  381. * @return $this
  382. *
  383. * @see SortableIterator
  384. */
  385. public function sortByAccessedTime()
  386. {
  387. $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
  388. return $this;
  389. }
  390. /**
  391. * Sorts files and directories by the last inode changed time.
  392. *
  393. * This is the time that the inode information was last modified (permissions, owner, group or other metadata).
  394. *
  395. * On Windows, since inode is not available, changed time is actually the file creation time.
  396. *
  397. * This can be slow as all the matching files and directories must be retrieved for comparison.
  398. *
  399. * @return $this
  400. *
  401. * @see SortableIterator
  402. */
  403. public function sortByChangedTime()
  404. {
  405. $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
  406. return $this;
  407. }
  408. /**
  409. * Sorts files and directories by the last modified time.
  410. *
  411. * This is the last time the actual contents of the file were last modified.
  412. *
  413. * This can be slow as all the matching files and directories must be retrieved for comparison.
  414. *
  415. * @return $this
  416. *
  417. * @see SortableIterator
  418. */
  419. public function sortByModifiedTime()
  420. {
  421. $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
  422. return $this;
  423. }
  424. /**
  425. * Filters the iterator with an anonymous function.
  426. *
  427. * The anonymous function receives a \SplFileInfo and must return false
  428. * to remove files.
  429. *
  430. * @return $this
  431. *
  432. * @see CustomFilterIterator
  433. */
  434. public function filter(\Closure $closure)
  435. {
  436. $this->filters[] = $closure;
  437. return $this;
  438. }
  439. /**
  440. * Forces the following of symlinks.
  441. *
  442. * @return $this
  443. */
  444. public function followLinks()
  445. {
  446. $this->followLinks = true;
  447. return $this;
  448. }
  449. /**
  450. * Tells finder to ignore unreadable directories.
  451. *
  452. * By default, scanning unreadable directories content throws an AccessDeniedException.
  453. *
  454. * @param bool $ignore
  455. *
  456. * @return $this
  457. */
  458. public function ignoreUnreadableDirs($ignore = true)
  459. {
  460. $this->ignoreUnreadableDirs = (bool) $ignore;
  461. return $this;
  462. }
  463. /**
  464. * Searches files and directories which match defined rules.
  465. *
  466. * @param string|array $dirs A directory path or an array of directories
  467. *
  468. * @return $this
  469. *
  470. * @throws \InvalidArgumentException if one of the directories does not exist
  471. */
  472. public function in($dirs)
  473. {
  474. $resolvedDirs = array();
  475. foreach ((array) $dirs as $dir) {
  476. if (is_dir($dir)) {
  477. $resolvedDirs[] = $dir;
  478. } elseif ($glob = glob($dir, (defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) {
  479. $resolvedDirs = array_merge($resolvedDirs, $glob);
  480. } else {
  481. throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
  482. }
  483. }
  484. $this->dirs = array_merge($this->dirs, $resolvedDirs);
  485. return $this;
  486. }
  487. /**
  488. * Returns an Iterator for the current Finder configuration.
  489. *
  490. * This method implements the IteratorAggregate interface.
  491. *
  492. * @return \Iterator|SplFileInfo[] An iterator
  493. *
  494. * @throws \LogicException if the in() method has not been called
  495. */
  496. public function getIterator()
  497. {
  498. if (0 === count($this->dirs) && 0 === count($this->iterators)) {
  499. throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
  500. }
  501. if (1 === count($this->dirs) && 0 === count($this->iterators)) {
  502. return $this->searchInDirectory($this->dirs[0]);
  503. }
  504. $iterator = new \AppendIterator();
  505. foreach ($this->dirs as $dir) {
  506. $iterator->append($this->searchInDirectory($dir));
  507. }
  508. foreach ($this->iterators as $it) {
  509. $iterator->append($it);
  510. }
  511. return $iterator;
  512. }
  513. /**
  514. * Appends an existing set of files/directories to the finder.
  515. *
  516. * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
  517. *
  518. * @param mixed $iterator
  519. *
  520. * @return $this
  521. *
  522. * @throws \InvalidArgumentException when the given argument is not iterable
  523. */
  524. public function append($iterator)
  525. {
  526. if ($iterator instanceof \IteratorAggregate) {
  527. $this->iterators[] = $iterator->getIterator();
  528. } elseif ($iterator instanceof \Iterator) {
  529. $this->iterators[] = $iterator;
  530. } elseif ($iterator instanceof \Traversable || is_array($iterator)) {
  531. $it = new \ArrayIterator();
  532. foreach ($iterator as $file) {
  533. $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
  534. }
  535. $this->iterators[] = $it;
  536. } else {
  537. throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
  538. }
  539. return $this;
  540. }
  541. /**
  542. * Counts all the results collected by the iterators.
  543. *
  544. * @return int
  545. */
  546. public function count()
  547. {
  548. return iterator_count($this->getIterator());
  549. }
  550. /**
  551. * @param $dir
  552. *
  553. * @return \Iterator
  554. */
  555. private function searchInDirectory($dir)
  556. {
  557. if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
  558. $this->exclude = array_merge($this->exclude, self::$vcsPatterns);
  559. }
  560. if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
  561. $this->notPaths[] = '#(^|/)\..+(/|$)#';
  562. }
  563. $minDepth = 0;
  564. $maxDepth = PHP_INT_MAX;
  565. foreach ($this->depths as $comparator) {
  566. switch ($comparator->getOperator()) {
  567. case '>':
  568. $minDepth = $comparator->getTarget() + 1;
  569. break;
  570. case '>=':
  571. $minDepth = $comparator->getTarget();
  572. break;
  573. case '<':
  574. $maxDepth = $comparator->getTarget() - 1;
  575. break;
  576. case '<=':
  577. $maxDepth = $comparator->getTarget();
  578. break;
  579. default:
  580. $minDepth = $maxDepth = $comparator->getTarget();
  581. }
  582. }
  583. $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
  584. if ($this->followLinks) {
  585. $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
  586. }
  587. $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
  588. if ($this->exclude) {
  589. $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
  590. }
  591. $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
  592. if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) {
  593. $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
  594. }
  595. if ($this->mode) {
  596. $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
  597. }
  598. if ($this->names || $this->notNames) {
  599. $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
  600. }
  601. if ($this->contains || $this->notContains) {
  602. $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
  603. }
  604. if ($this->sizes) {
  605. $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
  606. }
  607. if ($this->dates) {
  608. $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
  609. }
  610. if ($this->filters) {
  611. $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
  612. }
  613. if ($this->paths || $this->notPaths) {
  614. $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
  615. }
  616. if ($this->sort) {
  617. $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
  618. $iterator = $iteratorAggregate->getIterator();
  619. }
  620. return $iterator;
  621. }
  622. }