AnnotationDirectoryLoader.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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\Resource\DirectoryResource;
  12. use Symfony\Component\Routing\RouteCollection;
  13. /**
  14. * AnnotationDirectoryLoader loads routing information from annotations set
  15. * on PHP classes and methods.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class AnnotationDirectoryLoader extends AnnotationFileLoader
  20. {
  21. /**
  22. * @throws \InvalidArgumentException When the directory does not exist or its routes cannot be parsed
  23. */
  24. public function load(mixed $path, string $type = null): ?RouteCollection
  25. {
  26. if (!is_dir($dir = $this->locator->locate($path))) {
  27. return parent::supports($path, $type) ? parent::load($path, $type) : new RouteCollection();
  28. }
  29. $collection = new RouteCollection();
  30. $collection->addResource(new DirectoryResource($dir, '/\.php$/'));
  31. $files = iterator_to_array(new \RecursiveIteratorIterator(
  32. new \RecursiveCallbackFilterIterator(
  33. new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  34. function (\SplFileInfo $current) {
  35. return '.' !== substr($current->getBasename(), 0, 1);
  36. }
  37. ),
  38. \RecursiveIteratorIterator::LEAVES_ONLY
  39. ));
  40. usort($files, function (\SplFileInfo $a, \SplFileInfo $b) {
  41. return (string) $a > (string) $b ? 1 : -1;
  42. });
  43. foreach ($files as $file) {
  44. if (!$file->isFile() || !str_ends_with($file->getFilename(), '.php')) {
  45. continue;
  46. }
  47. if ($class = $this->findClass($file)) {
  48. $refl = new \ReflectionClass($class);
  49. if ($refl->isAbstract()) {
  50. continue;
  51. }
  52. $collection->addCollection($this->loader->load($class, $type));
  53. }
  54. }
  55. return $collection;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function supports(mixed $resource, string $type = null): bool
  61. {
  62. if ('annotation' === $type) {
  63. return true;
  64. }
  65. if ($type || !\is_string($resource)) {
  66. return false;
  67. }
  68. try {
  69. return is_dir($this->locator->locate($resource));
  70. } catch (\Exception $e) {
  71. return false;
  72. }
  73. }
  74. }