Ingen beskrivning

AnnotationDirectoryLoader.php 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. * Loads from annotations from a directory.
  23. *
  24. * @param string $path A directory path
  25. * @param string|null $type The resource type
  26. *
  27. * @return RouteCollection A RouteCollection instance
  28. *
  29. * @throws \InvalidArgumentException When the directory does not exist or its routes cannot be parsed
  30. */
  31. public function load($path, $type = null)
  32. {
  33. if (!is_dir($dir = $this->locator->locate($path))) {
  34. return parent::supports($path, $type) ? parent::load($path, $type) : new RouteCollection();
  35. }
  36. $collection = new RouteCollection();
  37. $collection->addResource(new DirectoryResource($dir, '/\.php$/'));
  38. $files = iterator_to_array(new \RecursiveIteratorIterator(
  39. new \RecursiveCallbackFilterIterator(
  40. new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  41. function (\SplFileInfo $current) {
  42. return '.' !== substr($current->getBasename(), 0, 1);
  43. }
  44. ),
  45. \RecursiveIteratorIterator::LEAVES_ONLY
  46. ));
  47. usort($files, function (\SplFileInfo $a, \SplFileInfo $b) {
  48. return (string) $a > (string) $b ? 1 : -1;
  49. });
  50. foreach ($files as $file) {
  51. if (!$file->isFile() || !str_ends_with($file->getFilename(), '.php')) {
  52. continue;
  53. }
  54. if ($class = $this->findClass($file)) {
  55. $refl = new \ReflectionClass($class);
  56. if ($refl->isAbstract()) {
  57. continue;
  58. }
  59. $collection->addCollection($this->loader->load($class, $type));
  60. }
  61. }
  62. return $collection;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function supports($resource, $type = null)
  68. {
  69. if ('annotation' === $type) {
  70. return true;
  71. }
  72. if ($type || !\is_string($resource)) {
  73. return false;
  74. }
  75. try {
  76. return is_dir($this->locator->locate($resource));
  77. } catch (\Exception $e) {
  78. return false;
  79. }
  80. }
  81. }