Facade.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 Facade
  12. {
  13. /**
  14. * @param array|string $paths
  15. * @param array|string $suffixes
  16. * @param array|string $prefixes
  17. * @param array $exclude
  18. * @param bool $commonPath
  19. *
  20. * @return array
  21. */
  22. public function getFilesAsArray($paths, $suffixes = '', $prefixes = '', array $exclude = [], bool $commonPath = false): array
  23. {
  24. if (\is_string($paths)) {
  25. $paths = [$paths];
  26. }
  27. $factory = new Factory;
  28. $iterator = $factory->getFileIterator($paths, $suffixes, $prefixes, $exclude);
  29. $files = [];
  30. foreach ($iterator as $file) {
  31. $file = $file->getRealPath();
  32. if ($file) {
  33. $files[] = $file;
  34. }
  35. }
  36. foreach ($paths as $path) {
  37. if (\is_file($path)) {
  38. $files[] = \realpath($path);
  39. }
  40. }
  41. $files = \array_unique($files);
  42. \sort($files);
  43. if ($commonPath) {
  44. return [
  45. 'commonPath' => $this->getCommonPath($files),
  46. 'files' => $files
  47. ];
  48. }
  49. return $files;
  50. }
  51. protected function getCommonPath(array $files): string
  52. {
  53. $count = \count($files);
  54. if ($count === 0) {
  55. return '';
  56. }
  57. if ($count === 1) {
  58. return \dirname($files[0]) . DIRECTORY_SEPARATOR;
  59. }
  60. $_files = [];
  61. foreach ($files as $file) {
  62. $_files[] = $_fileParts = \explode(DIRECTORY_SEPARATOR, $file);
  63. if (empty($_fileParts[0])) {
  64. $_fileParts[0] = DIRECTORY_SEPARATOR;
  65. }
  66. }
  67. $common = '';
  68. $done = false;
  69. $j = 0;
  70. $count--;
  71. while (!$done) {
  72. for ($i = 0; $i < $count; $i++) {
  73. if ($_files[$i][$j] != $_files[$i + 1][$j]) {
  74. $done = true;
  75. break;
  76. }
  77. }
  78. if (!$done) {
  79. $common .= $_files[0][$j];
  80. if ($j > 0) {
  81. $common .= DIRECTORY_SEPARATOR;
  82. }
  83. }
  84. $j++;
  85. }
  86. return DIRECTORY_SEPARATOR . $common;
  87. }
  88. }