association-1.0.0-alpha2/src/ContextProvider/AssociationRouteContext.php
src/ContextProvider/AssociationRouteContext.php
<?php namespace Drupal\association\ContextProvider; use Drupal\association\AssociationNegotiatorInterface; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Plugin\Context\Context; use Drupal\Core\Plugin\Context\ContextProviderInterface; use Drupal\Core\Plugin\Context\EntityContext; use Drupal\Core\Plugin\Context\EntityContextDefinition; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; /** * Provides a context for an association entity from the current route. */ class AssociationRouteContext implements ContextProviderInterface { use StringTranslationTrait; /** * The route match object. * * @var \Drupal\Core\Routing\RouteMatchInterface */ protected $routeMatch; /** * The association negotiator, to fetch the active association for the route. * * @var \Drupal\association\AssociationNegotiatorInterface */ protected $assocNegotiator; /** * Constructs an instance of the AssociationRouteContext class. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route match object. * @param \Drupal\association\AssociationNegotiatorInterface $association_negotiator * The association negotiator, fetches the active association for the route. */ public function __construct(RouteMatchInterface $route_match, AssociationNegotiatorInterface $association_negotiator) { $this->routeMatch = $route_match; $this->assocNegotiator = $association_negotiator; } /** * {@inheritdoc} */ public function getRuntimeContexts(array $unqualified_context_ids) { if ($association = $this->assocNegotiator->byRoute($this->routeMatch)) { $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['route.association']); $contextDef = EntityContextDefinition::fromEntityTypeId('association') ->setLabel($this->t('Entity Association from the current route.')) ->setRequired(FALSE); $context = new Context($contextDef, $association); $context->addCacheableDependency($cacheability); return ['association' => $context]; } return []; } /** * {@inheritdoc} */ public function getAvailableContexts() { $context = EntityContext::fromEntityTypeId('association', $this->t('Entity Association from the current route.')); return ['association' => $context]; } }