PhpFileLoader.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. public function load(mixed $file, ?string $type = null): RouteCollection
  30. {
  31. $path = $this->locator->locate($file);
  32. $this->setCurrentDir(\dirname($path));
  33. // the closure forbids access to the private scope in the included file
  34. $loader = $this;
  35. $load = \Closure::bind(static function ($file) use ($loader) {
  36. return include $file;
  37. }, null, ProtectedPhpFileLoader::class);
  38. $result = $load($path);
  39. if (\is_object($result) && \is_callable($result)) {
  40. $collection = $this->callConfigurator($result, $path, $file);
  41. } else {
  42. $collection = $result;
  43. }
  44. $collection->addResource(new FileResource($path));
  45. return $collection;
  46. }
  47. public function supports(mixed $resource, ?string $type = null): bool
  48. {
  49. return \is_string($resource) && 'php' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'php' === $type);
  50. }
  51. protected function callConfigurator(callable $result, string $path, string $file): RouteCollection
  52. {
  53. $collection = new RouteCollection();
  54. $result(new RoutingConfigurator($collection, $this, $path, $file, $this->env));
  55. return $collection;
  56. }
  57. }
  58. /**
  59. * @internal
  60. */
  61. final class ProtectedPhpFileLoader extends PhpFileLoader
  62. {
  63. }