PhpFileLoader.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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\Routing\Loader;
  11. use Symfony\Component\Config\Loader\FileLoader;
  12. use Symfony\Component\Config\Resource\FileResource;
  13. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
  14. use Symfony\Component\Routing\RouteCollection;
  15. /**
  16. * PhpFileLoader loads routes from a PHP file.
  17. *
  18. * The file must return a RouteCollection instance.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class PhpFileLoader extends FileLoader
  23. {
  24. /**
  25. * Loads a PHP file.
  26. *
  27. * @param string $file A PHP file path
  28. * @param string|null $type The resource type
  29. *
  30. * @return RouteCollection A RouteCollection instance
  31. */
  32. public function load($file, $type = null)
  33. {
  34. $path = $this->locator->locate($file);
  35. $this->setCurrentDir(\dirname($path));
  36. // the closure forbids access to the private scope in the included file
  37. $loader = $this;
  38. $load = \Closure::bind(function ($file) use ($loader) {
  39. return include $file;
  40. }, null, ProtectedPhpFileLoader::class);
  41. $result = $load($path);
  42. if (\is_object($result) && \is_callable($result)) {
  43. $collection = new RouteCollection();
  44. $result(new RoutingConfigurator($collection, $this, $path, $file), $this);
  45. } else {
  46. $collection = $result;
  47. }
  48. $collection->addResource(new FileResource($path));
  49. return $collection;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function supports($resource, $type = null)
  55. {
  56. return \is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'php' === $type);
  57. }
  58. }
  59. /**
  60. * @internal
  61. */
  62. final class ProtectedPhpFileLoader extends PhpFileLoader
  63. {
  64. }