2e10a8a643c5ea4b4aa45731c11432cea7789264
[yaffs-website] / web / core / modules / node / src / ContextProvider / NodeRouteContext.php
1 <?php
2
3 namespace Drupal\node\ContextProvider;
4
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Plugin\Context\Context;
7 use Drupal\Core\Plugin\Context\ContextDefinition;
8 use Drupal\Core\Plugin\Context\ContextProviderInterface;
9 use Drupal\Core\Routing\RouteMatchInterface;
10 use Drupal\node\Entity\Node;
11 use Drupal\Core\StringTranslation\StringTranslationTrait;
12
13 /**
14  * Sets the current node as a context on node routes.
15  */
16 class NodeRouteContext implements ContextProviderInterface {
17
18   use StringTranslationTrait;
19
20   /**
21    * The route match object.
22    *
23    * @var \Drupal\Core\Routing\RouteMatchInterface
24    */
25   protected $routeMatch;
26
27   /**
28    * Constructs a new NodeRouteContext.
29    *
30    * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
31    *   The route match object.
32    */
33   public function __construct(RouteMatchInterface $route_match) {
34     $this->routeMatch = $route_match;
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   public function getRuntimeContexts(array $unqualified_context_ids) {
41     $result = [];
42     $context_definition = new ContextDefinition('entity:node', NULL, FALSE);
43     $value = NULL;
44     if (($route_object = $this->routeMatch->getRouteObject()) && ($route_contexts = $route_object->getOption('parameters')) && isset($route_contexts['node'])) {
45       if ($node = $this->routeMatch->getParameter('node')) {
46         $value = $node;
47       }
48     }
49     elseif ($this->routeMatch->getRouteName() == 'node.add') {
50       $node_type = $this->routeMatch->getParameter('node_type');
51       $value = Node::create(['type' => $node_type->id()]);
52     }
53
54     $cacheability = new CacheableMetadata();
55     $cacheability->setCacheContexts(['route']);
56
57     $context = new Context($context_definition, $value);
58     $context->addCacheableDependency($cacheability);
59     $result['node'] = $context;
60
61     return $result;
62   }
63
64   /**
65    * {@inheritdoc}
66    */
67   public function getAvailableContexts() {
68     $context = new Context(new ContextDefinition('entity:node', $this->t('Node from URL')));
69     return ['node' => $context];
70   }
71
72 }