3 namespace Drupal\Core\Routing;
5 use Drupal\Core\Routing\Enhancer\RouteEnhancerInterface;
6 use Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface as BaseRouteEnhancerInterface;
7 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
8 use Symfony\Component\DependencyInjection\ContainerAwareInterface;
9 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
10 use Symfony\Component\HttpFoundation\Request;
11 use Symfony\Component\Routing\RouteCollection;
14 * A route enhancer which lazily loads route enhancers, depending on the route.
16 * We lazy initialize route enhancers, because otherwise all dependencies of
17 * all route enhancers are initialized on every request, which is slow. However,
18 * with the use of lazy loading, dependencies are instantiated only when used.
20 class LazyRouteEnhancer implements BaseRouteEnhancerInterface, ContainerAwareInterface {
22 use ContainerAwareTrait;
25 * Array of enhancers service IDs.
29 protected $serviceIds = [];
32 * The initialized route enhancers.
34 * @var \Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface[]|\Drupal\Core\Routing\Enhancer\RouteEnhancerInterface[]
36 protected $enhancers = NULL;
39 * Constructs the LazyRouteEnhancer object.
42 * Array of enhancers service IDs.
44 public function __construct($service_ids) {
45 $this->serviceIds = $service_ids;
49 * For each route, saves a list of applicable enhancers to the route.
51 * @param \Symfony\Component\Routing\RouteCollection $route_collection
52 * A collection of routes to apply enhancer checks to.
54 public function setEnhancers(RouteCollection $route_collection) {
55 /** @var \Symfony\Component\Routing\Route $route **/
56 foreach ($route_collection as $route_name => $route) {
58 foreach ($this->getEnhancers() as $service_id => $enhancer) {
59 if ((!$enhancer instanceof RouteEnhancerInterface) || $enhancer->applies($route)) {
60 $service_ids[] = $service_id;
64 $route->setOption('_route_enhancers', array_unique($service_ids));
70 * For each route, gets a list of applicable enhancer to the route.
72 * @return \Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface[]|\Drupal\Core\Routing\Enhancer\RouteEnhancerInterface[]
74 protected function getEnhancers() {
75 if (!isset($this->enhancers)) {
76 foreach ($this->serviceIds as $service_id) {
77 $this->enhancers[$service_id] = $this->container->get($service_id);
80 return $this->enhancers;
86 public function enhance(array $defaults, Request $request) {
87 /** @var \Symfony\Component\Routing\Route $route */
88 $route = $defaults[RouteObjectInterface::ROUTE_OBJECT];
90 $enhancer_ids = $route->getOption('_route_enhancers');
92 if (isset($enhancer_ids)) {
93 foreach ($enhancer_ids as $enhancer_id) {
94 $defaults = $this->container->get($enhancer_id)->enhance($defaults, $request);