FileLocator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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($name, $currentPath = null, $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. * @param string $file A file path
  66. *
  67. * @return bool
  68. */
  69. private function isAbsolutePath($file)
  70. {
  71. if ('/' === $file[0] || '\\' === $file[0]
  72. || (\strlen($file) > 3 && ctype_alpha($file[0])
  73. && ':' === $file[1]
  74. && ('\\' === $file[2] || '/' === $file[2])
  75. )
  76. || null !== parse_url($file, PHP_URL_SCHEME)
  77. ) {
  78. return true;
  79. }
  80. return false;
  81. }
  82. }