NodeRouteContext.php 2.55 KB
Newer Older
1 2
<?php

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\ContextProviderInterface;
8 9
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
10
use Drupal\Core\Routing\RouteMatchInterface;
11
use Drupal\node\Entity\Node;
12
use Drupal\Core\StringTranslation\StringTranslationTrait;
13 14 15 16

/**
 * Sets the current node as a context on node routes.
 */
17
class NodeRouteContext implements ContextProviderInterface {
18

19 20
  use StringTranslationTrait;

21
  /**
22
   * The route match object.
23
   *
24
   * @var \Drupal\Core\Routing\RouteMatchInterface
25
   */
26
  protected $routeMatch;
27 28 29 30

  /**
   * Constructs a new NodeRouteContext.
   *
31 32
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
33
   */
34 35
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
36 37 38 39 40
  }

  /**
   * {@inheritdoc}
   */
41 42
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $result = [];
43
    $context_definition = EntityContextDefinition::create('node')->setRequired(FALSE);
44
    $value = NULL;
45 46 47 48 49 50 51 52 53
    if (($route_object = $this->routeMatch->getRouteObject())) {
      $route_contexts = $route_object->getOption('parameters');
      // Check for a node revision parameter first.
      // @todo https://www.drupal.org/i/2730631 will allow to use the upcasted
      //   node revision object.
      if ($revision_id = $this->routeMatch->getRawParameter('node_revision')) {
        $value = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($revision_id);
      }
      elseif (isset($route_contexts['node']) && $node = $this->routeMatch->getParameter('node')) {
54
        $value = $node;
55
      }
56 57 58 59 60 61 62
      elseif (isset($route_contexts['node_preview']) && $node = $this->routeMatch->getParameter('node_preview')) {
        $value = $node;
      }
      elseif ($this->routeMatch->getRouteName() == 'node.add') {
        $node_type = $this->routeMatch->getParameter('node_type');
        $value = Node::create(['type' => $node_type->id()]);
      }
63
    }
64

65 66
    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['route']);
67 68

    $context = new Context($context_definition, $value);
69
    $context->addCacheableDependency($cacheability);
70 71 72
    $result['node'] = $context;

    return $result;
73 74
  }

75 76 77
  /**
   * {@inheritdoc}
   */
78
  public function getAvailableContexts() {
79
    $context = EntityContext::fromEntityTypeId('node', $this->t('Node from URL'));
80
    return ['node' => $context];
81 82
  }

83
}