association-1.0.0-alpha2/src/Cache/Context/AssociationRouteCacheContext.php

src/Cache/Context/AssociationRouteCacheContext.php
<?php

namespace Drupal\association\Cache\Context;

use Drupal\association\AssociationNegotiatorInterface;
use Drupal\association\Entity\AssociationInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Create a cache context for the active association from a route.
 *
 * Cache context ID: 'route.association'
 */
class AssociationRouteCacheContext implements CacheContextInterface {

  /**
   * Information about a route, typically this is matching the current route.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * The association negotiator, determines the active association.
   *
   * @var \Drupal\association\AssociationNegotiatorInterface
   */
  protected $assocNegotiator;

  /**
   * Create a new instance of the AssociationRouteCacheContext class.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   A route match object to get parameter and user information from.
   * @param \Drupal\association\AssociationNegotiatorInterface $association_negotiator
   *   The association negotiator, determines the active association for the
   *   route match.
   */
  public function __construct(RouteMatchInterface $route_match, AssociationNegotiatorInterface $association_negotiator) {
    $this->routeMatch = $route_match;
    $this->assocNegotiator = $association_negotiator;
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return new TranslatableMarkup('Association by route');
  }

  /**
   * Get the association for this route if one can be determined.
   *
   * @return \Drupal\association\Entity\AssociationInterface|null
   *   The association linked to this route if there is one.
   */
  protected function getAssociation(): ?AssociationInterface {
    if ($entityParam = $this->routeMatch->getParameter('association_entity_type')) {
      $entity = $this->routeMatch->getParameter($entityParam);
      return $entity ? $this->assocNegotiator->byEntity($entity) : NULL;
    }
    else {
      return $this->assocNegotiator->byRoute($this->routeMatch);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    $assoc = $this->getAssociation();
    return $assoc ? $assoc->id() : 0;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc