AnnotationDirectoryLoader.php 2.2 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\Routing\RouteCollection;
  12. use Symfony\Component\Config\Resource\DirectoryResource;
  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. $dir = $this->locator->locate($path);
  34. $collection = new RouteCollection();
  35. $collection->addResource(new DirectoryResource($dir, '/\.php$/'));
  36. $files = iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY));
  37. usort($files, function (\SplFileInfo $a, \SplFileInfo $b) {
  38. return (string) $a > (string) $b ? 1 : -1;
  39. });
  40. foreach ($files as $file) {
  41. if (!$file->isFile() || '.php' !== substr($file->getFilename(), -4)) {
  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. /**
  55. * {@inheritdoc}
  56. */
  57. public function supports($resource, $type = null)
  58. {
  59. try {
  60. $path = $this->locator->locate($resource);
  61. } catch (\Exception $e) {
  62. return false;
  63. }
  64. return is_string($resource) && is_dir($path) && (!$type || 'annotation' === $type);
  65. }
  66. }