RngEventRouteContext.php in RNG - Events and Registrations 8
File
src/ContextProvider/RngEventRouteContext.php
View source
<?php
namespace Drupal\rng\ContextProvider;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\rng\EventManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Entity\EntityInterface;
class RngEventRouteContext implements ContextProviderInterface {
use StringTranslationTrait;
protected $routeMatch;
protected $eventManager;
public function __construct(RouteMatchInterface $route_match, EventManagerInterface $event_manager) {
$this->routeMatch = $route_match;
$this->eventManager = $event_manager;
}
public function getRuntimeContexts(array $unqualified_context_ids) {
$cacheability = new CacheableMetadata();
$cacheability
->setCacheContexts([
'rng_event',
]);
$context_definition = new ContextDefinition('entity', NULL, FALSE);
$context = new Context($context_definition, $this
->getEventInRoute());
$context
->addCacheableDependency($cacheability);
return [
'rng_event' => $context,
];
}
public function getAvailableContexts() {
$context = new Context(new ContextDefinition('entity', $this
->t('RNG event from route')));
return [
'rng_event' => $context,
];
}
protected function getEventInRoute() {
if (!($route = $this->routeMatch
->getRouteObject())) {
return NULL;
}
if ($event_param = $route
->getDefault('event')) {
$event = $this->routeMatch
->getParameter($event_param);
return $event instanceof EntityInterface ? $event : NULL;
}
if ($events = $this
->getEventEntitiesInRoute()) {
foreach ($events as $entity) {
foreach ($entity
->getEntityType()
->getLinkTemplates() as $link_template => $path) {
if ($route
->getPath() === $path) {
return $entity;
}
}
if ($canonical_path = $entity
->getEntityType()
->getLinkTemplate('canonical')) {
if (strpos($route
->getPath(), $canonical_path) === 0) {
return $entity;
}
}
}
}
return NULL;
}
protected function getEventEntitiesInRoute() {
$events = [];
if (($route = $this->routeMatch
->getRouteObject()) && ($parameters = $route
->getOption('parameters'))) {
foreach ($parameters as $parameter) {
if (isset($parameter['type']) && strpos($parameter['type'], 'entity:') !== FALSE) {
$entity_type_id = substr($parameter['type'], strlen('entity:'));
$entity = $this->routeMatch
->getParameter($entity_type_id);
if ($entity instanceof EntityInterface && $this->eventManager
->isEvent($entity)) {
$events[] = $entity;
}
}
}
}
return $events;
}
}