rules-8.x-3.x-dev/src/Context/ExecutionState.php

src/Context/ExecutionState.php
<?php

declare(strict_types=1);

namespace Drupal\rules\Context;

use Drupal\Core\TypedData\Exception\MissingDataException;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\Core\TypedData\TypedDataTrait;
use Drupal\rules\Exception\EvaluationException;
use Drupal\rules\Exception\InvalidArgumentException;
use Drupal\typed_data\DataFetcherTrait;

/**
 * The Rules execution state.
 *
 * A Rule element may clone the state, so any added variables are only visible
 * for elements in the current PHP-variable-scope.
 */
class ExecutionState implements ExecutionStateInterface {
  use DataFetcherTrait;
  use GlobalContextRepositoryTrait;
  use TypedDataTrait;

  /**
   * Globally keeps the ids of rules blocked due to recursion prevention.
   *
   * @var array
   *
   * @todo Implement recursion prevention from D7.
   * @todo Move this out of Context namespace?
   * @see https://www.drupal.org/project/rules/issues/2677094
   */
  protected static $blocked = [];

  /**
   * The known variables.
   *
   * @var \Drupal\Core\TypedData\TypedDataInterface[]
   */
  protected $variables = [];

  /**
   * Holds variables for auto-saving later.
   *
   * @var array
   */
  protected $saveLater = [];

  /**
   * Variable for saving currently blocked configs for serialization.
   *
   * @var array
   */
  protected $currentlyBlocked;

  /**
   * Constructs the object.
   *
   * @param \Drupal\Core\TypedData\TypedDataInterface[] $variables
   *   (optional) Variables to initialize this state with.
   */
  protected function __construct(array $variables) {
    $this->variables = $variables;
  }

  /**
   * Creates the object.
   *
   * @param \Drupal\Core\TypedData\TypedDataInterface[] $variables
   *   (optional) Variables to initialize this state with.
   *
   * @return static
   */
  public static function create(array $variables = []): static {
    return new static($variables);
  }

  /**
   * {@inheritdoc}
   */
  public function setVariable(string $name, ContextDefinitionInterface $definition, $value): static {
    $data = $this->getTypedDataManager()->create(
      $definition->getDataDefinition(),
      $value
    );
    $this->setVariableData($name, $data);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setVariableData(string $name, TypedDataInterface $data): static {
    $this->variables[$name] = $data;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getVariable(string $name): TypedDataInterface {
    if (!$this->hasVariable($name)) {
      // @todo This crashes site in certain circumstances - for example if
      // you're reacting on a "Drupal is initializing" event ... Need to handle
      // a problem here gracefully - maybe disable the rule that caused the
      // problem?
      throw new EvaluationException("Unable to get variable '$name'; it is not defined.");
    }
    return $this->variables[$name];
  }

  /**
   * {@inheritdoc}
   */
  public function getVariableValue(string $name): string {
    return $this->getVariable($name)->getValue();
  }

  /**
   * {@inheritdoc}
   */
  public function hasVariable(string $name): bool {
    if (!array_key_exists($name, $this->variables)) {
      // If there is no such variable, lazy-add global context variables. That
      // way we can save time fetching global context if it is not needed.
      if (!($name[0] === '@' && strpos($name, ':') !== FALSE)) {
        return FALSE;
      }
      $contexts = $this->getGlobalContextRepository()->getRuntimeContexts([$name]);
      if (!array_key_exists($name, $contexts)) {
        return FALSE;
      }
      $this->setVariableData($name, $contexts[$name]->getContextData());
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function removeVariable(string $name): static {
    if (array_key_exists($name, $this->variables)) {
      unset($this->variables[$name]);
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function fetchDataByPropertyPath(string $property_path, ?string $langcode = NULL): TypedDataInterface {
    try {
      // Support global context names as variable name by ignoring points in
      // the service name; e.g. @user.current_user_context:current_user.name.
      if ($property_path[0] == '@') {
        [$service, $property_path] = explode(':', $property_path, 2);
      }
      $parts = explode('.', $property_path);
      $var_name = array_shift($parts);
      if (isset($service)) {
        $var_name = $service . ':' . $var_name;
      }
      return $this
        ->getDataFetcher()
        ->fetchDataBySubPaths($this->getVariable($var_name), $parts, $langcode);
    }
    catch (InvalidArgumentException $e) {
      // Pass on the original exception in the exception trace.
      throw new EvaluationException($e->getMessage(), 0, $e);
    }
    catch (MissingDataException $e) {
      // Pass on the original exception in the exception trace.
      throw new EvaluationException($e->getMessage(), 0, $e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function saveChangesLater(string $selector): static {
    $this->saveLater[$selector] = TRUE;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getAutoSaveSelectors(): array {
    return array_keys($this->saveLater);
  }

  /**
   * {@inheritdoc}
   */
  public function autoSave(): static {
    // Make changes permanent.
    foreach ($this->saveLater as $selector => $flag) {
      $typed_data = $this->fetchDataByPropertyPath($selector);
      // Things that can be saved must have a save() method, right?
      // Saving is always done at the root of the typed data tree, for example
      // on the entity level.
      $typed_data->getRoot()->getValue()->save();
    }
    return $this;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc