class ConditionExpression

Defines an executable condition expression.

This plugin is used to wrap condition plugins and is responsible to setup all the context necessary, instantiate the condition plugin and to execute it.

Plugin annotation


@RulesExpression(
  id = "rules_condition",
  label = @Translation("Condition"),
  form_class = "\Drupal\rules\Form\Expression\ConditionForm"
)

Hierarchy

Expanded class hierarchy of ConditionExpression

1 file declares its use of ConditionExpression
ConditionExpressionTest.php in tests/src/Unit/ConditionExpressionTest.php

File

src/Plugin/RulesExpression/ConditionExpression.php, line 30

Namespace

Drupal\rules\Plugin\RulesExpression
View source
class ConditionExpression extends ExpressionBase implements ConditionExpressionInterface, ContainerFactoryPluginInterface {
    use ContextHandlerIntegrityTrait;
    
    /**
     * The condition manager used to instantiate the condition plugin.
     *
     * @var \Drupal\rules\Core\ConditionManager
     */
    protected $conditionManager;
    
    /**
     * The rules debug logger channel.
     *
     * @var \Drupal\Core\Logger\LoggerChannelInterface
     */
    protected $rulesDebugLogger;
    
    /**
     * Constructs a new class instance.
     *
     * @param array $configuration
     *   A configuration array containing information about the plugin instance.
     *   Contains the following entries:
     *   - condition_id: The condition plugin ID.
     * @param string $plugin_id
     *   The plugin ID for the plugin instance.
     * @param mixed $plugin_definition
     *   The plugin implementation definition.
     * @param \Drupal\rules\Core\ConditionManager $condition_manager
     *   The condition manager.
     * @param \Drupal\rules\Context\DataProcessorManager $processor_manager
     *   The data processor plugin manager.
     * @param \Drupal\Core\Logger\LoggerChannelInterface $logger
     *   The Rules debug logger channel.
     */
    public function __construct(array $configuration, $plugin_id, $plugin_definition, ConditionManager $condition_manager, DataProcessorManager $processor_manager, LoggerChannelInterface $logger) {
        // Make sure defaults are applied.
        $configuration += $this->defaultConfiguration();
        parent::__construct($configuration, $plugin_id, $plugin_definition);
        $this->conditionManager = $condition_manager;
        $this->processorManager = $processor_manager;
        $this->rulesDebugLogger = $logger;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static($configuration, $plugin_id, $plugin_definition, $container->get('plugin.manager.condition'), $container->get('plugin.manager.rules_data_processor'), $container->get('logger.channel.rules_debug'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function defaultConfiguration() {
        return [
            // Per default the result of this expression is not negated.
'negate' => FALSE,
        ];
    }
    
    /**
     * {@inheritdoc}
     */
    public function setConfiguration(array $configuration) {
        // If the plugin id has been set already, keep it if not specified.
        if (isset($this->configuration['condition_id'])) {
            $configuration += [
                'condition_id' => $this->configuration['condition_id'],
            ];
        }
        return parent::setConfiguration($configuration);
    }
    
    /**
     * {@inheritdoc}
     */
    public function executeWithState(ExecutionStateInterface $state) {
        $condition = $this->conditionManager
            ->createInstance($this->configuration['condition_id'], [
            'negate' => $this->configuration['negate'],
        ]);
        $this->prepareContext($condition, $state);
        $result = $condition->evaluate();
        if ($this->isNegated()) {
            $result = !$result;
        }
        $this->rulesDebugLogger
            ->info('The condition %name evaluated to %bool.', [
            '%name' => $this->getLabel(),
            '%bool' => $result ? 'TRUE' : 'FALSE',
            'element' => $this,
        ]);
        // Now that the condition has been executed it can provide additional
        // context which we will have to pass back in the evaluation state.
        $this->addProvidedContext($condition, $state);
        return $result;
    }
    
    /**
     * {@inheritdoc}
     */
    public function negate($negate = TRUE) {
        $this->configuration['negate'] = $negate;
        return $this;
    }
    
    /**
     * {@inheritdoc}
     */
    public function isNegated() {
        return !empty($this->configuration['negate']);
    }
    
    /**
     * {@inheritdoc}
     */
    public function getLabel() {
        if (!empty($this->configuration['condition_id'])) {
            $definition = $this->conditionManager
                ->getDefinition($this->configuration['condition_id']);
            if ($this->isNegated()) {
                return $this->t('@not @label', [
                    '@not' => $this->t('NOT'),
                    '@label' => $definition['label'],
                ]);
            }
            else {
                return $definition['label'];
            }
        }
        return parent::getLabel();
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormHandler() {
        if (isset($this->pluginDefinition['form_class'])) {
            $class_name = $this->pluginDefinition['form_class'];
            return new $class_name($this, $this->conditionManager);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function checkIntegrity(ExecutionMetadataStateInterface $metadata_state, $apply_assertions = TRUE) {
        $violation_list = new IntegrityViolationList();
        if (empty($this->configuration['condition_id'])) {
            $violation_list->addViolationWithMessage($this->t('Condition plugin ID is missing'), $this->getUuid());
            return $violation_list;
        }
        if (!$this->conditionManager
            ->hasDefinition($this->configuration['condition_id'])) {
            $violation_list->addViolationWithMessage($this->t('Condition plugin %plugin_id does not exist', [
                '%plugin_id' => $this->configuration['condition_id'],
            ]), $this->getUuid());
            return $violation_list;
        }
        $condition = $this->conditionManager
            ->createInstance($this->configuration['condition_id'], [
            'negate' => $this->configuration['negate'],
        ]);
        // Prepare and refine the context before checking integrity, such that any
        // context definition changes are respected while checking.
        $this->prepareContextWithMetadata($condition, $metadata_state);
        $result = $this->checkContextConfigIntegrity($condition, $metadata_state);
        $this->prepareExecutionMetadataState($metadata_state, NULL, $apply_assertions);
        return $result;
    }
    
    /**
     * {@inheritdoc}
     */
    public function prepareExecutionMetadataState(ExecutionMetadataStateInterface $metadata_state, ExpressionInterface $until = NULL, $apply_assertions = TRUE) {
        if ($until && $this->getUuid() === $until->getUuid()) {
            return TRUE;
        }
        $condition = $this->conditionManager
            ->createInstance($this->configuration['condition_id'], [
            'negate' => $this->configuration['negate'],
        ]);
        // Make sure to refine context first, such that possibly refined definitions
        // of provided context are respected.
        $this->prepareContextWithMetadata($condition, $metadata_state);
        $this->addProvidedContextDefinitions($condition, $metadata_state);
        if ($apply_assertions && !$this->isNegated()) {
            $this->assertMetadata($condition, $metadata_state);
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
ConditionExpression::$conditionManager protected property The condition manager used to instantiate the condition plugin.
ConditionExpression::$rulesDebugLogger protected property The rules debug logger channel.
ConditionExpression::checkIntegrity public function Verifies that this expression is configured correctly. Overrides ExpressionInterface::checkIntegrity
ConditionExpression::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ConditionExpression::defaultConfiguration public function Gets default configuration for this plugin. Overrides ExpressionBase::defaultConfiguration
ConditionExpression::executeWithState public function Execute the expression with a given Rules state. Overrides ExpressionInterface::executeWithState
ConditionExpression::getFormHandler public function Returns the form handling class for this expression. Overrides ExpressionBase::getFormHandler
ConditionExpression::getLabel public function The label of this expression element that can be shown in the UI. Overrides ExpressionBase::getLabel
ConditionExpression::isNegated public function Determines whether condition result will be negated. Overrides ConditionExpressionInterface::isNegated
ConditionExpression::negate public function Negates the result after evaluating this condition. Overrides ConditionExpressionInterface::negate
ConditionExpression::prepareExecutionMetadataState public function Prepares the execution metadata state by adding metadata to it. Overrides ExpressionInterface::prepareExecutionMetadataState
ConditionExpression::setConfiguration public function Sets the configuration for this plugin instance. Overrides ExpressionBase::setConfiguration
ConditionExpression::__construct public function Constructs a new class instance. Overrides ExpressionBase::__construct
ContextHandlerIntegrityTrait::checkContextConfigIntegrity protected function Performs the integrity check.
ContextHandlerIntegrityTrait::checkDataTypeCompatible protected function Checks that the data type of a mapped variable matches the expectation.
ContextHandlerTrait::$processorManager protected property The data processor plugin manager used to process context variables.
ContextHandlerTrait::addProvidedContext protected function Adds provided context values from the plugin to the execution state.
ContextHandlerTrait::addProvidedContextDefinitions protected function Adds the definitions of provided context to the execution metadata state.
ContextHandlerTrait::assertMetadata protected function Asserts additional metadata.
ContextHandlerTrait::getMappedDefinition protected function Gets the definition of the data that is mapped to the given context.
ContextHandlerTrait::getSelectedData protected function Gets definitions of all selected data at configuration time.
ContextHandlerTrait::prepareContext protected function Prepares plugin context based upon the set context configuration.
ContextHandlerTrait::prepareContextWithMetadata protected function Prepares plugin context based upon the set context configuration.
ContextHandlerTrait::processData protected function Process data context on the plugin, usually before it gets executed.
ContextHandlerTrait::processValue protected function Processes a single value.
ExpressionBase::$configEntityId protected property The config entity this expression is associated with, if any.
ExpressionBase::$configuration protected property The plugin configuration.
ExpressionBase::$root protected property The root expression if this object is nested.
ExpressionBase::$uuid protected property The UUID of this expression.
ExpressionBase::$weight protected property The weight (list order) of this expression.
ExpressionBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ExpressionBase::execute public function Executes a rules expression. Overrides ExecutableInterface::execute
ExpressionBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration 3
ExpressionBase::getRoot public function Returns the root expression if this expression is nested. Overrides ExpressionInterface::getRoot
ExpressionBase::getUuid public function Returns the UUID of this expression if it is nested in another expression. Overrides ExpressionInterface::getUuid
ExpressionBase::getWeight public function Returns the list order of this expression. Overrides ExpressionInterface::getWeight
ExpressionBase::setRoot public function Set the root expression for this expression if it is nested. Overrides ExpressionInterface::setRoot
ExpressionBase::setUuid public function Sets the UUID of this expression in an expression tree. Overrides ExpressionInterface::setUuid
ExpressionBase::setWeight public function Sets the list order of this expression in an expression tree. Overrides ExpressionInterface::setWeight
PluginInspectionInterface::getPluginDefinition public function Gets the definition of the plugin implementation. 6
PluginInspectionInterface::getPluginId public function Gets the plugin_id of the plugin instance. 2