ContextAwarePluginTrait.php 7.59 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
<?php

namespace Drupal\Core\Plugin;

use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Component\Plugin\Context\ContextInterface as ComponentContextInterface;
use Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface;
use Drupal\Component\Plugin\Exception\ContextException;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextInterface;
use Symfony\Component\Validator\ConstraintViolationList;

/**
 * Provides a trait to add context-aware functionality to plugins.
 *
 * @see \Drupal\Core\Plugin\ContextAwarePluginInterface
 *
 * @ingroup plugin_api
 */
trait ContextAwarePluginTrait {

  /**
   * The data objects representing the context of this plugin.
   *
   * @var \Drupal\Core\Plugin\Context\ContextInterface[]
   */
  protected $context = [];

  /**
   * Tracks whether the context has been initialized from configuration.
   *
   * @var bool
   *
   * @todo Remove this in Drupal 10.0.x.
   *   See https://www.drupal.org/project/drupal/issues/3153956.
   *
   * @internal
   */
  protected $initializedContextConfig = FALSE;

  /**
   * {@inheritdoc}
   */
  public function getContexts() {
    // Make sure all context objects are initialized.
    foreach ($this->getContextDefinitions() as $name => $definition) {
      $this->getContext($name);
    }
    return $this->context;
  }

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\Core\Plugin\Context\ContextInterface
   *   The context object.
   */
  public function getContext($name) {
    // @todo Remove this entire block in Drupal 10.0.x.
    //   See https://www.drupal.org/project/drupal/issues/3153956.
    if (!$this->initializedContextConfig) {
      $this->initializedContextConfig = TRUE;
      if ($this instanceof ConfigurableInterface) {
        $configuration = $this->getConfiguration();
      }
      else {
        $reflection = new \ReflectionProperty($this, 'configuration');
        $reflection->setAccessible(TRUE);
        $configuration = $reflection->getValue($this);
      }

      if (isset($configuration['context'])) {
        @trigger_error('Passing context values to plugins via configuration is deprecated in drupal:9.1.0 and will be removed before drupal:10.0.0. Instead, call ::setContextValue() on the plugin itself. See https://www.drupal.org/node/3120980', E_USER_DEPRECATED);
        foreach ($configuration['context'] as $key => $value) {
          $context_definition = $this->getContextDefinition($key);
          $this->context[$key] = new Context($context_definition, $value);
        }
      }
    }

    // Check for a valid context value.
    if (!isset($this->context[$name])) {
      $this->context[$name] = new Context($this->getContextDefinition($name));
    }
    return $this->context[$name];
  }

  /**
   * {@inheritdoc}
   */
  public function setContext($name, ComponentContextInterface $context) {
    // Check that the context passed is an instance of our extended interface.
    if (!$context instanceof ContextInterface) {
      throw new ContextException("Passed $name context must be an instance of \\Drupal\\Core\\Plugin\\Context\\ContextInterface");
    }
    $this->context[$name] = $context;
  }

  /**
   * {@inheritdoc}
   */
  public function getContextValues() {
    $values = [];
    foreach ($this->getContextDefinitions() as $name => $definition) {
      $values[$name] = isset($this->context[$name]) ? $this->context[$name]->getContextValue() : NULL;
    }
    return $values;
  }

  /**
   * {@inheritdoc}
   */
  public function getContextValue($name) {
    return $this->getContext($name)->getContextValue();
  }

  /**
   * {@inheritdoc}
   */
  public function setContextValue($name, $value) {
    $this->setContext($name, Context::createFromContext($this->getContext($name), $value));
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getContextMapping() {
    $configuration = $this instanceof ConfigurableInterface ? $this->getConfiguration() : $this->configuration;
    return isset($configuration['context_mapping']) ? $configuration['context_mapping'] : [];
  }

  /**
   * {@inheritdoc}
   */
  public function setContextMapping(array $context_mapping) {
    if ($this instanceof ConfigurableInterface) {
      $configuration = $this->getConfiguration();
      $configuration['context_mapping'] = array_filter($context_mapping);
      $this->setConfiguration($configuration);
    }
    else {
      $this->configuration['context_mapping'] = $context_mapping;
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  abstract protected function getPluginDefinition();

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface[]
   */
  public function getContextDefinitions() {
    $definition = $this->getPluginDefinition();
    if ($definition instanceof ContextAwarePluginDefinitionInterface) {
      return $definition->getContextDefinitions();
    }

    return !empty($definition['context_definitions']) ? $definition['context_definitions'] : [];
  }

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface
   */
  public function getContextDefinition($name) {
    $definition = $this->getPluginDefinition();
    if ($definition instanceof ContextAwarePluginDefinitionInterface) {
      if ($definition->hasContextDefinition($name)) {
        return $definition->getContextDefinition($name);
      }
    }
    elseif (!empty($definition['context_definitions'][$name])) {
      return $definition['context_definitions'][$name];
    }
    throw new ContextException(sprintf("The %s context is not a valid context.", $name));
  }

  /**
   * {@inheritdoc}
   */
  public function validateContexts() {
    $violations = new ConstraintViolationList();

    // @todo Implement the Symfony Validator component to let the validator
    //   traverse and set property paths accordingly.
    //   See https://www.drupal.org/project/drupal/issues/3153847.
    foreach ($this->getContexts() as $context) {
      $violations->addAll($context->validate());
    }
    return $violations;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $cache_contexts = [];
    // Applied contexts can affect the cache contexts when this plugin is
    // involved in caching, collect and return them.
    foreach ($this->getContexts() as $context) {
210
      /** @var \Drupal\Core\Cache\CacheableDependencyInterface $context */
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
      if ($context instanceof CacheableDependencyInterface) {
        $cache_contexts = Cache::mergeContexts($cache_contexts, $context->getCacheContexts());
      }
    }
    return $cache_contexts;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $tags = [];
    // Applied contexts can affect the cache tags when this plugin is
    // involved in caching, collect and return them.
    foreach ($this->getContexts() as $context) {
226
      /** @var \Drupal\Core\Cache\CacheableDependencyInterface $context */
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      if ($context instanceof CacheableDependencyInterface) {
        $tags = Cache::mergeTags($tags, $context->getCacheTags());
      }
    }
    return $tags;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    $max_age = Cache::PERMANENT;

    // Applied contexts can affect the cache max age when this plugin is
    // involved in caching, collect and return them.
    foreach ($this->getContexts() as $context) {
243
      /** @var \Drupal\Core\Cache\CacheableDependencyInterface $context */
244 245 246 247 248 249 250 251
      if ($context instanceof CacheableDependencyInterface) {
        $max_age = Cache::mergeMaxAges($max_age, $context->getCacheMaxAge());
      }
    }
    return $max_age;
  }

}