ContextAwarePluginBase.php in Service Container 7
File
lib/Drupal/Component/Plugin/ContextAwarePluginBase.php
View source
<?php
namespace Drupal\Component\Plugin;
use Drupal\Component\Plugin\Context\ContextInterface;
use Drupal\Component\Plugin\Exception\ContextException;
use Drupal\Component\Plugin\Context\Context;
use Symfony\Component\Validator\ConstraintViolationList;
abstract class ContextAwarePluginBase extends PluginBase implements ContextAwarePluginInterface {
protected $context = [];
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
$context_configuration = isset($configuration['context']) ? $configuration['context'] : [];
unset($configuration['context']);
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->contexts = $this
->createContextFromConfiguration($context_configuration);
}
protected function createContextFromConfiguration(array $context_configuration) {
$contexts = [];
foreach ($context_configuration as $key => $value) {
$context_definition = $this
->getContextDefinition($key);
$contexts[$key] = new Context($context_definition, $value);
}
return $contexts;
}
public function getContextDefinitions() {
$definition = $this
->getPluginDefinition();
return !empty($definition['context']) ? $definition['context'] : array();
}
public function getContextDefinition($name) {
$definition = $this
->getPluginDefinition();
if (empty($definition['context'][$name])) {
throw new ContextException(sprintf("The %s context is not a valid context.", $name));
}
return $definition['context'][$name];
}
public function getContexts() {
foreach ($this
->getContextDefinitions() as $name => $definition) {
$this
->getContext($name);
}
return $this->context;
}
public function getContext($name) {
if (!isset($this->context[$name])) {
$this->context[$name] = new Context($this
->getContextDefinition($name));
}
return $this->context[$name];
}
public function setContext($name, ContextInterface $context) {
$this->context[$name] = $context;
}
public function getContextValues() {
$values = array();
foreach ($this
->getContextDefinitions() as $name => $definition) {
$values[$name] = isset($this->context[$name]) ? $this->context[$name]
->getContextValue() : NULL;
}
return $values;
}
public function getContextValue($name) {
return $this
->getContext($name)
->getContextValue();
}
public function setContextValue($name, $value) {
$this->context[$name] = new Context($this
->getContextDefinition($name), $value);
return $this;
}
public function validateContexts() {
$violations = new ConstraintViolationList();
foreach ($this
->getContexts() as $context) {
$violations
->addAll($context
->validate());
}
return $violations;
}
}