4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Routing\Loader
;
14 use Symfony\Component\Routing\RouteCollection
;
15 use Symfony\Component\Config\
Resource\FileResource
;
16 use Symfony\Component\Config\Loader\FileLoader
;
17 use Symfony\Component\Config\FileLocatorInterface
;
20 * AnnotationFileLoader loads routing information from annotations set
21 * on a PHP class and its methods.
23 * @author Fabien Potencier <fabien@symfony.com>
25 class AnnotationFileLoader
extends FileLoader
32 * @param FileLocatorInterface $locator A FileLocator instance
33 * @param AnnotationClassLoader $loader An AnnotationClassLoader instance
34 * @param string|array $paths A path or an array of paths where to look for resources
36 * @throws \RuntimeException
38 public function __construct(FileLocatorInterface
$locator, AnnotationClassLoader
$loader, $paths = array())
40 if (!function_exists('token_get_all')) {
41 throw new \
RuntimeException('The Tokenizer extension is required for the routing annotation loaders.');
44 parent
::__construct($locator, $paths);
46 $this->loader
= $loader;
50 * Loads from annotations from a file.
52 * @param string $file A PHP file path
53 * @param string|null $type The resource type
55 * @return RouteCollection A RouteCollection instance
57 * @throws \InvalidArgumentException When the file does not exist or its routes cannot be parsed
59 public function load($file, $type = null)
61 $path = $this->locator
->locate($file);
63 $collection = new RouteCollection();
64 if ($class = $this->findClass($path)) {
65 $collection->addResource(new FileResource($path));
66 $collection->addCollection($this->loader
->load($class, $type));
75 public function supports($resource, $type = null)
77 return is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION
) && (!$type || 'annotation' === $type);
81 * Returns the full class name for the first class in the file.
83 * @param string $file A PHP file path
85 * @return string|false Full class name if found, false otherwise
87 protected function findClass($file)
91 $tokens = token_get_all(file_get_contents($file));
92 for ($i = 0, $count = count($tokens); $i < $count; $i++
) {
95 if (!is_array($token)) {
99 if (true === $class && T_STRING
=== $token[0]) {
100 return $namespace.'\\'.$token[1];
103 if (true === $namespace && T_STRING
=== $token[0]) {
106 $namespace .= $token[1];
107 $token = $tokens[++
$i];
108 } while ($i < $count && is_array($token) && in_array($token[0], array(T_NS_SEPARATOR
, T_STRING
)));
111 if (T_CLASS
=== $token[0]) {
115 if (T_NAMESPACE
=== $token[0]) {