AnnotationClassLoader.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 Doctrine\Common\Annotations\Reader;
  12. use Symfony\Component\Config\Loader\LoaderInterface;
  13. use Symfony\Component\Config\Loader\LoaderResolverInterface;
  14. use Symfony\Component\Config\Resource\FileResource;
  15. use Symfony\Component\Routing\Route;
  16. use Symfony\Component\Routing\RouteCollection;
  17. /**
  18. * AnnotationClassLoader loads routing information from a PHP class and its methods.
  19. *
  20. * You need to define an implementation for the getRouteDefaults() method. Most of the
  21. * time, this method should define some PHP callable to be called for the route
  22. * (a controller in MVC speak).
  23. *
  24. * The @Route annotation can be set on the class (for global parameters),
  25. * and on each method.
  26. *
  27. * The @Route annotation main value is the route path. The annotation also
  28. * recognizes several parameters: requirements, options, defaults, schemes,
  29. * methods, host, and name. The name parameter is mandatory.
  30. * Here is an example of how you should be able to use it:
  31. *
  32. * /**
  33. * * @Route("/Blog")
  34. * * /
  35. * class Blog
  36. * {
  37. * /**
  38. * * @Route("/", name="blog_index")
  39. * * /
  40. * public function index()
  41. * {
  42. * }
  43. *
  44. * /**
  45. * * @Route("/{id}", name="blog_post", requirements = {"id" = "\d+"})
  46. * * /
  47. * public function show()
  48. * {
  49. * }
  50. * }
  51. *
  52. * @author Fabien Potencier <fabien@symfony.com>
  53. */
  54. abstract class AnnotationClassLoader implements LoaderInterface
  55. {
  56. protected $reader;
  57. /**
  58. * @var string
  59. */
  60. protected $routeAnnotationClass = 'Symfony\\Component\\Routing\\Annotation\\Route';
  61. /**
  62. * @var int
  63. */
  64. protected $defaultRouteIndex = 0;
  65. public function __construct(Reader $reader)
  66. {
  67. $this->reader = $reader;
  68. }
  69. /**
  70. * Sets the annotation class to read route properties from.
  71. *
  72. * @param string $class A fully-qualified class name
  73. */
  74. public function setRouteAnnotationClass($class)
  75. {
  76. $this->routeAnnotationClass = $class;
  77. }
  78. /**
  79. * Loads from annotations from a class.
  80. *
  81. * @param string $class A class name
  82. * @param string|null $type The resource type
  83. *
  84. * @return RouteCollection A RouteCollection instance
  85. *
  86. * @throws \InvalidArgumentException When route can't be parsed
  87. */
  88. public function load($class, $type = null)
  89. {
  90. if (!class_exists($class)) {
  91. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  92. }
  93. $class = new \ReflectionClass($class);
  94. if ($class->isAbstract()) {
  95. throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName()));
  96. }
  97. $globals = $this->getGlobals($class);
  98. $collection = new RouteCollection();
  99. $collection->addResource(new FileResource($class->getFileName()));
  100. foreach ($class->getMethods() as $method) {
  101. $this->defaultRouteIndex = 0;
  102. foreach ($this->reader->getMethodAnnotations($method) as $annot) {
  103. if ($annot instanceof $this->routeAnnotationClass) {
  104. $this->addRoute($collection, $annot, $globals, $class, $method);
  105. }
  106. }
  107. }
  108. return $collection;
  109. }
  110. protected function addRoute(RouteCollection $collection, $annot, $globals, \ReflectionClass $class, \ReflectionMethod $method)
  111. {
  112. $name = $annot->getName();
  113. if (null === $name) {
  114. $name = $this->getDefaultRouteName($class, $method);
  115. }
  116. $defaults = array_replace($globals['defaults'], $annot->getDefaults());
  117. foreach ($method->getParameters() as $param) {
  118. if (false !== strpos($globals['path'].$annot->getPath(), sprintf('{%s}', $param->getName())) && !isset($defaults[$param->getName()]) && $param->isDefaultValueAvailable()) {
  119. $defaults[$param->getName()] = $param->getDefaultValue();
  120. }
  121. }
  122. $requirements = array_replace($globals['requirements'], $annot->getRequirements());
  123. $options = array_replace($globals['options'], $annot->getOptions());
  124. $schemes = array_merge($globals['schemes'], $annot->getSchemes());
  125. $methods = array_merge($globals['methods'], $annot->getMethods());
  126. $host = $annot->getHost();
  127. if (null === $host) {
  128. $host = $globals['host'];
  129. }
  130. $condition = $annot->getCondition();
  131. if (null === $condition) {
  132. $condition = $globals['condition'];
  133. }
  134. $route = $this->createRoute($globals['path'].$annot->getPath(), $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  135. $this->configureRoute($route, $class, $method, $annot);
  136. $collection->add($name, $route);
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function supports($resource, $type = null)
  142. {
  143. return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'annotation' === $type);
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. public function setResolver(LoaderResolverInterface $resolver)
  149. {
  150. }
  151. /**
  152. * {@inheritdoc}
  153. */
  154. public function getResolver()
  155. {
  156. }
  157. /**
  158. * Gets the default route name for a class method.
  159. *
  160. * @param \ReflectionClass $class
  161. * @param \ReflectionMethod $method
  162. *
  163. * @return string
  164. */
  165. protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
  166. {
  167. $name = strtolower(str_replace('\\', '_', $class->name).'_'.$method->name);
  168. if ($this->defaultRouteIndex > 0) {
  169. $name .= '_'.$this->defaultRouteIndex;
  170. }
  171. ++$this->defaultRouteIndex;
  172. return $name;
  173. }
  174. protected function getGlobals(\ReflectionClass $class)
  175. {
  176. $globals = array(
  177. 'path' => '',
  178. 'requirements' => array(),
  179. 'options' => array(),
  180. 'defaults' => array(),
  181. 'schemes' => array(),
  182. 'methods' => array(),
  183. 'host' => '',
  184. 'condition' => '',
  185. );
  186. if ($annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)) {
  187. // for BC reasons
  188. if (null !== $annot->getPath()) {
  189. $globals['path'] = $annot->getPath();
  190. } elseif (null !== $annot->getPattern()) {
  191. $globals['path'] = $annot->getPattern();
  192. }
  193. if (null !== $annot->getRequirements()) {
  194. $globals['requirements'] = $annot->getRequirements();
  195. }
  196. if (null !== $annot->getOptions()) {
  197. $globals['options'] = $annot->getOptions();
  198. }
  199. if (null !== $annot->getDefaults()) {
  200. $globals['defaults'] = $annot->getDefaults();
  201. }
  202. if (null !== $annot->getSchemes()) {
  203. $globals['schemes'] = $annot->getSchemes();
  204. }
  205. if (null !== $annot->getMethods()) {
  206. $globals['methods'] = $annot->getMethods();
  207. }
  208. if (null !== $annot->getHost()) {
  209. $globals['host'] = $annot->getHost();
  210. }
  211. if (null !== $annot->getCondition()) {
  212. $globals['condition'] = $annot->getCondition();
  213. }
  214. }
  215. return $globals;
  216. }
  217. protected function createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition)
  218. {
  219. return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  220. }
  221. abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot);
  222. }