FileLocator.php 2.3 KB

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