Factory.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of php-file-iterator.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  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 SebastianBergmann\FileIterator;
  11. class Factory
  12. {
  13. /**
  14. * @param array|string $paths
  15. * @param array|string $suffixes
  16. * @param array|string $prefixes
  17. * @param array $exclude
  18. *
  19. * @return \AppendIterator
  20. */
  21. public function getFileIterator($paths, $suffixes = '', $prefixes = '', array $exclude = []): \AppendIterator
  22. {
  23. if (\is_string($paths)) {
  24. $paths = [$paths];
  25. }
  26. $paths = $this->getPathsAfterResolvingWildcards($paths);
  27. $exclude = $this->getPathsAfterResolvingWildcards($exclude);
  28. if (\is_string($prefixes)) {
  29. if ($prefixes !== '') {
  30. $prefixes = [$prefixes];
  31. } else {
  32. $prefixes = [];
  33. }
  34. }
  35. if (\is_string($suffixes)) {
  36. if ($suffixes !== '') {
  37. $suffixes = [$suffixes];
  38. } else {
  39. $suffixes = [];
  40. }
  41. }
  42. $iterator = new \AppendIterator;
  43. foreach ($paths as $path) {
  44. if (\is_dir($path)) {
  45. $iterator->append(
  46. new Iterator(
  47. $path,
  48. new \RecursiveIteratorIterator(
  49. new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS | \RecursiveDirectoryIterator::SKIP_DOTS)
  50. ),
  51. $suffixes,
  52. $prefixes,
  53. $exclude
  54. )
  55. );
  56. }
  57. }
  58. return $iterator;
  59. }
  60. protected function getPathsAfterResolvingWildcards(array $paths): array
  61. {
  62. $_paths = [[]];
  63. foreach ($paths as $path) {
  64. if ($locals = \glob($path, GLOB_ONLYDIR)) {
  65. $_paths[] = \array_map('\realpath', $locals);
  66. } else {
  67. $_paths[] = [\realpath($path)];
  68. }
  69. }
  70. return \array_filter(\array_merge(...$_paths));
  71. }
  72. }