AnnotationDirectoryLoader.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.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\FileResource;
  13. /**
  14. * AnnotationDirectoryLoader loads routing information from annotations set
  15. * on PHP classes and methods.
  16. *
  17. * @author Fabien Potencier <fabien.potencier@symfony-project.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 $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. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  36. if (!$file->isFile() || '.php' !== substr($file->getFilename(), -4)) {
  37. continue;
  38. }
  39. if ($class = $this->findClass($file)) {
  40. $collection->addResource(new FileResource($file));
  41. $collection->addCollection($this->loader->load($class, $type));
  42. }
  43. }
  44. return $collection;
  45. }
  46. /**
  47. * Returns true if this class supports the given resource.
  48. *
  49. * @param mixed $resource A resource
  50. * @param string $type The resource type
  51. *
  52. * @return Boolean True if this class supports the given resource, false otherwise
  53. */
  54. public function supports($resource, $type = null)
  55. {
  56. try {
  57. $path = $this->locator->locate($resource);
  58. } catch (\Exception $e) {
  59. return false;
  60. }
  61. return is_string($resource) && is_dir($path) && (!$type || 'annotation' === $type);
  62. }
  63. }