Context.php in Drupal 9
File
core/lib/Drupal/Component/Plugin/Context/Context.php
View source
<?php
namespace Drupal\Component\Plugin\Context;
use Drupal\Component\Plugin\Exception\ContextException;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Validation;
class Context implements ContextInterface {
protected $contextValue;
protected $contextDefinition;
public function __construct(ContextDefinitionInterface $context_definition, $context_value = NULL) {
$this->contextDefinition = $context_definition;
$this->contextValue = $context_value;
}
public function getContextValue() {
if (!isset($this->contextValue)) {
$definition = $this
->getContextDefinition();
$default_value = $definition
->getDefaultValue();
if (!isset($default_value) && $definition
->isRequired()) {
$type = $definition
->getDataType();
throw new ContextException(sprintf("The %s context is required and not present.", $type));
}
$this->contextValue = $default_value;
}
return $this->contextValue;
}
public function hasContextValue() {
return (bool) $this->contextValue || (bool) $this
->getContextDefinition()
->getDefaultValue();
}
public function getContextDefinition() {
return $this->contextDefinition;
}
public function getConstraints() {
if (empty($this->contextDefinition['class'])) {
throw new ContextException("An error was encountered while trying to validate the context.");
}
return [
new Type($this->contextDefinition['class']),
];
}
public function validate() {
$validator = Validation::createValidatorBuilder()
->getValidator();
return $validator
->validateValue($this
->getContextValue(), $this
->getConstraints());
}
}
Classes
Name |
Description |
Context |
A generic context class for wrapping data a plugin needs to operate. |