FileLocator.php 2.4 KB

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