ContextAwarePluginDefinitionTrait.php 1.8 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
<?php

namespace Drupal\Component\Plugin\Definition;

use Drupal\Component\Plugin\Context\ContextDefinitionInterface;
use Drupal\Component\Plugin\Exception\ContextException;

/**
 * Provides a trait for context-aware object-based plugin definitions.
 */
trait ContextAwarePluginDefinitionTrait {

  /**
   * The context definitions for this plugin definition.
   *
   * @var \Drupal\Component\Plugin\Context\ContextDefinitionInterface[]
   */
  protected $contextDefinitions = [];

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::hasContextDefinition().
   */
  public function hasContextDefinition($name) {
    return array_key_exists($name, $this->contextDefinitions);
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::getContextDefinitions().
   */
  public function getContextDefinitions() {
    return $this->contextDefinitions;
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::getContextDefinition().
   */
  public function getContextDefinition($name) {
    if ($this->hasContextDefinition($name)) {
      return $this->contextDefinitions[$name];
    }
    throw new ContextException($this->id() . " does not define a '$name' context");
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::addContextDefinition().
   */
  public function addContextDefinition($name, ContextDefinitionInterface $definition) {
    $this->contextDefinitions[$name] = $definition;
    return $this;
  }

  /**
   * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::removeContextDefinition().
   */
  public function removeContextDefinition($name) {
    unset($this->contextDefinitions[$name]);
    return $this;
  }

}