You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

3 years ago
  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. * @author Nicolas grekas <p@tchwork.com>
  22. * @author Jules Pietri <jules@heahprod.com>
  23. */
  24. class PhpFileLoader extends FileLoader
  25. {
  26. /**
  27. * Loads a PHP file.
  28. *
  29. * @param string $file A PHP file path
  30. * @param string|null $type The resource type
  31. *
  32. * @return RouteCollection A RouteCollection instance
  33. */
  34. public function load($file, string $type = null)
  35. {
  36. $path = $this->locator->locate($file);
  37. $this->setCurrentDir(\dirname($path));
  38. // the closure forbids access to the private scope in the included file
  39. $loader = $this;
  40. $load = \Closure::bind(static function ($file) use ($loader) {
  41. return include $file;
  42. }, null, ProtectedPhpFileLoader::class);
  43. $result = $load($path);
  44. if (\is_object($result) && \is_callable($result)) {
  45. $collection = $this->callConfigurator($result, $path, $file);
  46. } else {
  47. $collection = $result;
  48. }
  49. $collection->addResource(new FileResource($path));
  50. return $collection;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function supports($resource, string $type = null)
  56. {
  57. return \is_string($resource) && 'php' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'php' === $type);
  58. }
  59. protected function callConfigurator(callable $result, string $path, string $file): RouteCollection
  60. {
  61. $collection = new RouteCollection();
  62. $result(new RoutingConfigurator($collection, $this, $path, $file, $this->env));
  63. return $collection;
  64. }
  65. }
  66. /**
  67. * @internal
  68. */
  69. final class ProtectedPhpFileLoader extends PhpFileLoader
  70. {
  71. }