FileLocator.php 2.8 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. /**
  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. * Returns a full path for a given file name.
  30. *
  31. * @param mixed $name The file name to locate
  32. * @param string $currentPath The current path
  33. * @param Boolean $first Whether to return the first occurrence or an array of filenames
  34. *
  35. * @return string|array The full path to the file|An array of file paths
  36. *
  37. * @throws \InvalidArgumentException When file is not found
  38. */
  39. public function locate($name, $currentPath = null, $first = true)
  40. {
  41. if ($this->isAbsolutePath($name)) {
  42. if (!file_exists($name)) {
  43. throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $name));
  44. }
  45. return $name;
  46. }
  47. $filepaths = array();
  48. if (null !== $currentPath && file_exists($file = $currentPath.DIRECTORY_SEPARATOR.$name)) {
  49. if (true === $first) {
  50. return $file;
  51. }
  52. $filepaths[] = $file;
  53. }
  54. foreach ($this->paths as $path) {
  55. if (file_exists($file = $path.DIRECTORY_SEPARATOR.$name)) {
  56. if (true === $first) {
  57. return $file;
  58. }
  59. $filepaths[] = $file;
  60. }
  61. }
  62. if (!$filepaths) {
  63. throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s%s).', $name, null !== $currentPath ? $currentPath.', ' : '', implode(', ', $this->paths)));
  64. }
  65. return array_values(array_unique($filepaths));
  66. }
  67. /**
  68. * Returns whether the file path is an absolute path.
  69. *
  70. * @param string $file A file path
  71. *
  72. * @return Boolean
  73. */
  74. private function isAbsolutePath($file)
  75. {
  76. if ($file[0] == '/' || $file[0] == '\\'
  77. || (strlen($file) > 3 && ctype_alpha($file[0])
  78. && $file[1] == ':'
  79. && ($file[2] == '\\' || $file[2] == '/')
  80. )
  81. || null !== parse_url($file, PHP_URL_SCHEME)
  82. ) {
  83. return true;
  84. }
  85. return false;
  86. }
  87. }