FileLoader.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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\Loader;
  11. use Symfony\Component\Config\FileLocatorInterface;
  12. use Symfony\Component\Config\Exception\FileLoaderImportException;
  13. use Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException;
  14. /**
  15. * FileLoader is the abstract class used by all built-in loaders that are file based.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. abstract class FileLoader extends Loader
  20. {
  21. static protected $loading = array();
  22. protected $locator;
  23. private $currentDir;
  24. /**
  25. * Constructor.
  26. *
  27. * @param FileLocatorInterface $locator A FileLocatorInterface instance
  28. */
  29. public function __construct(FileLocatorInterface $locator)
  30. {
  31. $this->locator = $locator;
  32. }
  33. public function setCurrentDir($dir)
  34. {
  35. $this->currentDir = $dir;
  36. }
  37. public function getLocator()
  38. {
  39. return $this->locator;
  40. }
  41. /**
  42. * Imports a resource.
  43. *
  44. * @param mixed $resource A Resource
  45. * @param string $type The resource type
  46. * @param Boolean $ignoreErrors Whether to ignore import errors or not
  47. * @param string $sourceResource The original resource importing the new resource
  48. *
  49. * @return mixed
  50. */
  51. public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null)
  52. {
  53. try {
  54. $loader = $this->resolve($resource, $type);
  55. if ($loader instanceof FileLoader && null !== $this->currentDir) {
  56. $resource = $this->locator->locate($resource, $this->currentDir);
  57. }
  58. if (isset(self::$loading[$resource])) {
  59. throw new FileLoaderImportCircularReferenceException(array_keys(self::$loading));
  60. }
  61. self::$loading[$resource] = true;
  62. $ret = $loader->load($resource);
  63. unset(self::$loading[$resource]);
  64. return $ret;
  65. } catch (FileLoaderImportCircularReferenceException $e) {
  66. throw $e;
  67. } catch (\Exception $e) {
  68. if (!$ignoreErrors) {
  69. // prevent embedded imports from nesting multiple exceptions
  70. if ($e instanceof FileLoaderImportException) {
  71. throw $e;
  72. }
  73. throw new FileLoaderImportException($resource, $sourceResource, null, $e);
  74. }
  75. }
  76. }
  77. }