RecursiveRegexFinder.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Migrations\Finder;
  4. use FilesystemIterator;
  5. use RecursiveDirectoryIterator;
  6. use RecursiveIteratorIterator;
  7. use RegexIterator;
  8. use function sprintf;
  9. use const DIRECTORY_SEPARATOR;
  10. /**
  11. * The RecursiveRegexFinder class recursively searches the given directory for migrations.
  12. */
  13. final class RecursiveRegexFinder extends Finder
  14. {
  15. /** @var string */
  16. private $pattern;
  17. public function __construct(?string $pattern = null)
  18. {
  19. $this->pattern = $pattern ?? sprintf(
  20. '#^.+\\%s[^\\%s]+\\.php$#i',
  21. DIRECTORY_SEPARATOR,
  22. DIRECTORY_SEPARATOR
  23. );
  24. }
  25. /**
  26. * @return string[]
  27. */
  28. public function findMigrations(string $directory, ?string $namespace = null): array
  29. {
  30. $dir = $this->getRealPath($directory);
  31. return $this->loadMigrations(
  32. $this->getMatches($this->createIterator($dir)),
  33. $namespace
  34. );
  35. }
  36. private function createIterator(string $dir): RegexIterator
  37. {
  38. return new RegexIterator(
  39. new RecursiveIteratorIterator(
  40. new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS),
  41. RecursiveIteratorIterator::LEAVES_ONLY
  42. ),
  43. $this->getPattern(),
  44. RegexIterator::GET_MATCH
  45. );
  46. }
  47. private function getPattern(): string
  48. {
  49. return $this->pattern;
  50. }
  51. /**
  52. * @return string[]
  53. */
  54. private function getMatches(RegexIterator $iteratorFilesMatch): array
  55. {
  56. $files = [];
  57. foreach ($iteratorFilesMatch as $file) {
  58. $files[] = $file[0];
  59. }
  60. return $files;
  61. }
  62. }