FileLocator.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Config;
  11. use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException;
  12. /**
  13. * FileLocator uses an array of pre-defined paths to find files.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class FileLocator implements FileLocatorInterface
  18. {
  19. protected $paths;
  20. /**
  21. * @param string|string[] $paths A path or an array of paths where to look for resources
  22. */
  23. public function __construct($paths = [])
  24. {
  25. $this->paths = (array) $paths;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function locate(string $name, string $currentPath = null, bool $first = true)
  31. {
  32. if ('' === $name) {
  33. throw new \InvalidArgumentException('An empty file name is not valid to be located.');
  34. }
  35. if ($this->isAbsolutePath($name)) {
  36. if (!file_exists($name)) {
  37. throw new FileLocatorFileNotFoundException(sprintf('The file "%s" does not exist.', $name), 0, null, [$name]);
  38. }
  39. return $name;
  40. }
  41. $paths = $this->paths;
  42. if (null !== $currentPath) {
  43. array_unshift($paths, $currentPath);
  44. }
  45. $paths = array_unique($paths);
  46. $filepaths = $notfound = [];
  47. foreach ($paths as $path) {
  48. if (@file_exists($file = $path.\DIRECTORY_SEPARATOR.$name)) {
  49. if (true === $first) {
  50. return $file;
  51. }
  52. $filepaths[] = $file;
  53. } else {
  54. $notfound[] = $file;
  55. }
  56. }
  57. if (!$filepaths) {
  58. throw new FileLocatorFileNotFoundException(sprintf('The file "%s" does not exist (in: "%s").', $name, implode('", "', $paths)), 0, null, $notfound);
  59. }
  60. return $filepaths;
  61. }
  62. /**
  63. * Returns whether the file path is an absolute path.
  64. */
  65. private function isAbsolutePath(string $file): bool
  66. {
  67. if ('/' === $file[0] || '\\' === $file[0]
  68. || (\strlen($file) > 3 && ctype_alpha($file[0])
  69. && ':' === $file[1]
  70. && ('\\' === $file[2] || '/' === $file[2])
  71. )
  72. || null !== parse_url($file, \PHP_URL_SCHEME)
  73. ) {
  74. return true;
  75. }
  76. return false;
  77. }
  78. }