3 namespace Drupal\node\ContextProvider;
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;
14 * Sets the current node as a context on node routes.
16 class NodeRouteContext implements ContextProviderInterface {
18 use StringTranslationTrait;
21 * The route match object.
23 * @var \Drupal\Core\Routing\RouteMatchInterface
25 protected $routeMatch;
28 * Constructs a new NodeRouteContext.
30 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
31 * The route match object.
33 public function __construct(RouteMatchInterface $route_match) {
34 $this->routeMatch = $route_match;
40 public function getRuntimeContexts(array $unqualified_context_ids) {
42 $context_definition = new ContextDefinition('entity:node', NULL, FALSE);
44 if (($route_object = $this->routeMatch->getRouteObject()) && ($route_contexts = $route_object->getOption('parameters')) && isset($route_contexts['node'])) {
45 if ($node = $this->routeMatch->getParameter('node')) {
49 elseif ($this->routeMatch->getRouteName() == 'node.add') {
50 $node_type = $this->routeMatch->getParameter('node_type');
51 $value = Node::create(['type' => $node_type->id()]);
54 $cacheability = new CacheableMetadata();
55 $cacheability->setCacheContexts(['route']);
57 $context = new Context($context_definition, $value);
58 $context->addCacheableDependency($cacheability);
59 $result['node'] = $context;
67 public function getAvailableContexts() {
68 $context = new Context(new ContextDefinition('entity:node', $this->t('Node from URL')));
69 return ['node' => $context];