annotate core/modules/node/src/ContextProvider/NodeRouteContext.php @ 0:4c8ae668cc8c

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