FileLocator.php 2.8 KB

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