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\Config\Loader\Loader;
15 use Symfony\Component\Config\Resource\FileResource;
16 use Symfony\Component\Routing\RouteCollection;
19 * A route loader that calls a method on an object to load the routes.
21 * @author Ryan Weaver <ryan@knpuniversity.com>
23 abstract class ObjectRouteLoader extends Loader
26 * Returns the object that the method will be called on to load routes.
28 * For example, if your application uses a service container,
29 * the $id may be a service id.
35 abstract protected function getServiceObject($id);
38 * Calls the service that will load the routes.
40 * @param mixed $resource Some value that will resolve to a callable
41 * @param string|null $type The resource type
43 * @return RouteCollection
45 public function load($resource, $type = null)
47 $parts = explode(':', $resource);
48 if (count($parts) != 2) {
49 throw new \InvalidArgumentException(sprintf('Invalid resource "%s" passed to the "service" route loader: use the format "service_name:methodName"', $resource));
52 $serviceString = $parts[0];
55 $loaderObject = $this->getServiceObject($serviceString);
57 if (!is_object($loaderObject)) {
58 throw new \LogicException(sprintf('%s:getServiceObject() must return an object: %s returned', get_class($this), gettype($loaderObject)));
61 if (!method_exists($loaderObject, $method)) {
62 throw new \BadMethodCallException(sprintf('Method "%s" not found on "%s" when importing routing resource "%s"', $method, get_class($loaderObject), $resource));
65 $routeCollection = call_user_func(array($loaderObject, $method), $this);
67 if (!$routeCollection instanceof RouteCollection) {
68 $type = is_object($routeCollection) ? get_class($routeCollection) : gettype($routeCollection);
70 throw new \LogicException(sprintf('The %s::%s method must return a RouteCollection: %s returned', get_class($loaderObject), $method, $type));
73 // make the service file tracked so that if it changes, the cache rebuilds
74 $this->addClassResource(new \ReflectionClass($loaderObject), $routeCollection);
76 return $routeCollection;
82 public function supports($resource, $type = null)
84 return 'service' === $type;
87 private function addClassResource(\ReflectionClass $class, RouteCollection $collection)
90 if (is_file($class->getFileName())) {
91 $collection->addResource(new FileResource($class->getFileName()));
93 } while ($class = $class->getParentClass());