Facade.php 2.6 KB

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