ContextAwarePluginDefinitionTrait.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Drupal\Component\Plugin\Definition;
  3. use Drupal\Component\Plugin\Context\ContextDefinitionInterface;
  4. use Drupal\Component\Plugin\Exception\ContextException;
  5. /**
  6. * Provides a trait for context-aware object-based plugin definitions.
  7. */
  8. trait ContextAwarePluginDefinitionTrait {
  9. /**
  10. * The context definitions for this plugin definition.
  11. *
  12. * @var \Drupal\Component\Plugin\Context\ContextDefinitionInterface[]
  13. */
  14. protected $contextDefinitions = [];
  15. /**
  16. * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::hasContextDefinition().
  17. */
  18. public function hasContextDefinition($name) {
  19. return array_key_exists($name, $this->contextDefinitions);
  20. }
  21. /**
  22. * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::getContextDefinitions().
  23. */
  24. public function getContextDefinitions() {
  25. return $this->contextDefinitions;
  26. }
  27. /**
  28. * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::getContextDefinition().
  29. */
  30. public function getContextDefinition($name) {
  31. if ($this->hasContextDefinition($name)) {
  32. return $this->contextDefinitions[$name];
  33. }
  34. throw new ContextException($this->id() . " does not define a '$name' context");
  35. }
  36. /**
  37. * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::addContextDefinition().
  38. */
  39. public function addContextDefinition($name, ContextDefinitionInterface $definition) {
  40. $this->contextDefinitions[$name] = $definition;
  41. return $this;
  42. }
  43. /**
  44. * Implements \Drupal\Component\Plugin\Definition\ContextAwarePluginDefinitionInterface::removeContextDefinition().
  45. */
  46. public function removeContextDefinition($name) {
  47. unset($this->contextDefinitions[$name]);
  48. return $this;
  49. }
  50. }