AttributeDirectoryLoader.php 2.6 KB

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