You are here

public function TransactionCreate::execute in Transaction 8

Executes the plugin.

Overrides RulesActionBase::execute

File

src/Plugin/RulesAction/TransactionCreate.php, line 81

Class

TransactionCreate
Provides the transaction create action.

Namespace

Drupal\transaction\Plugin\RulesAction

Code

public function execute() {
  $values = $this
    ->getContextValues();

  /** @var \Drupal\transaction\TransactionTypeInterface $transaction_type */
  if (!($transaction_type = $this->entityTypeManager
    ->getStorage('transaction_type')
    ->load($values['transaction_type_id']))) {

    // Transaction type not found.
    $this->logger
      ->error('Transaction type @type not found in action rule %rule', [
      '@type' => $values['transaction_type_id'],
      '%rule' => $this
        ->getLabelValue(),
    ]);
    return;
  }

  // Ensure that the transaction type has this transactor.
  if ($transaction_type
    ->getPluginId() != $this
    ->getDerivativeId()) {
    $this->logger
      ->error('Mismatch transactor in rule %rule for transaction type %type', [
      '%rule' => $this
        ->getLabelValue(),
      '%type' => $transaction_type
        ->label(),
    ]);
    return;
  }

  // Check if the transaction type is applicable to the given target entity.
  $target_entity = $values['target_entity'];
  if (!$transaction_type
    ->isApplicable($target_entity)) {
    $this->logger
      ->error('Transaction type %type not applicable to the target entity %target', [
      '%type' => $transaction_type
        ->label(),
      '%target' => $target_entity
        ->label(),
    ]);
    return;
  }

  // Create the transaction.

  /** @var \Drupal\transaction\TransactionInterface $transaction */
  $transaction = $this->entityTypeManager
    ->getStorage('transaction')
    ->create([
    'type' => $transaction_type
      ->id(),
    'target_entity' => $target_entity,
  ]);

  // Set the operation.
  if (!empty($values['operation_id'])) {
    $transaction
      ->setOperation($values['operation_id']);
  }

  // Set field values.
  $settings = $transaction_type
    ->getPluginSettings();
  foreach ([
    'transaction',
    'target',
  ] as $field_group) {
    $entity = $field_group == 'transaction' ? $transaction : $target_entity;
    $field_prefix = $field_group . '_field_';
    foreach ($values as $key => $value) {
      if (strpos($key, $field_prefix) === 0) {
        $transactor_field_name = substr($key, strlen($field_prefix));
        if (!empty($settings[$transactor_field_name]) && $entity
          ->hasField($settings[$transactor_field_name])) {
          $entity
            ->get($settings[$transactor_field_name])
            ->setValue($value);
        }
      }
    }
  }
  $this
    ->setProvidedValue('transaction', $transaction);
}