Factory.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /*
  3. * This file is part of the File_Iterator package.
  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. /**
  11. * Factory Method implementation that creates a File_Iterator that operates on
  12. * an AppendIterator that contains an RecursiveDirectoryIterator for each given
  13. * path.
  14. *
  15. * @since Class available since Release 1.1.0
  16. */
  17. class File_Iterator_Factory
  18. {
  19. /**
  20. * @param array|string $paths
  21. * @param array|string $suffixes
  22. * @param array|string $prefixes
  23. * @param array $exclude
  24. * @return AppendIterator
  25. */
  26. public function getFileIterator($paths, $suffixes = '', $prefixes = '', array $exclude = array())
  27. {
  28. if (is_string($paths)) {
  29. $paths = array($paths);
  30. }
  31. $paths = $this->getPathsAfterResolvingWildcards($paths);
  32. $exclude = $this->getPathsAfterResolvingWildcards($exclude);
  33. if (is_string($prefixes)) {
  34. if ($prefixes != '') {
  35. $prefixes = array($prefixes);
  36. } else {
  37. $prefixes = array();
  38. }
  39. }
  40. if (is_string($suffixes)) {
  41. if ($suffixes != '') {
  42. $suffixes = array($suffixes);
  43. } else {
  44. $suffixes = array();
  45. }
  46. }
  47. $iterator = new AppendIterator;
  48. foreach ($paths as $path) {
  49. if (is_dir($path)) {
  50. $iterator->append(
  51. new File_Iterator(
  52. new RecursiveIteratorIterator(
  53. new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::FOLLOW_SYMLINKS)
  54. ),
  55. $suffixes,
  56. $prefixes,
  57. $exclude,
  58. $path
  59. )
  60. );
  61. }
  62. }
  63. return $iterator;
  64. }
  65. /**
  66. * @param array $paths
  67. * @return array
  68. */
  69. protected function getPathsAfterResolvingWildcards(array $paths)
  70. {
  71. $_paths = array();
  72. foreach ($paths as $path) {
  73. if ($locals = glob($path, GLOB_ONLYDIR)) {
  74. $_paths = array_merge($_paths, $locals);
  75. } else {
  76. $_paths[] = $path;
  77. }
  78. }
  79. return $_paths;
  80. }
  81. }