You are here

public function BalanceTransactor::executeTransaction in Transaction 8

Executes a transaction.

By calling this method, the transactor will set the result code in the transaction.

Parameters

\Drupal\transaction\TransactionInterface $transaction: The transaction to execute.

\Drupal\transaction\TransactionInterface $last_executed: The last executed transaction with the same type and target. Empty if this is the first one.

Return value

bool TRUE if transaction was executed, FALSE otherwise.

Overrides GenericTransactor::executeTransaction

See also

\Drupal\transaction\TransactionInterface::getResultCode()

File

src/Plugin/Transaction/BalanceTransactor.php, line 62

Class

BalanceTransactor
Transactor for accounting type transactions.

Namespace

Drupal\transaction\Plugin\Transaction

Code

public function executeTransaction(TransactionInterface $transaction, TransactionInterface $last_executed = NULL) {
  if (!parent::executeTransaction($transaction, $last_executed)) {
    return FALSE;
  }
  $settings = $transaction
    ->getType()
    ->getPluginSettings();

  // Current balance from the last executed transaction. The current
  // transaction balance will take as the initial balance.
  $balance = $last_executed ? $last_executed
    ->get($settings['balance'])->value : $transaction
    ->get($settings['balance'])->value;

  // Transaction amount.
  $amount = $transaction
    ->get($settings['amount'])->value;

  // Set result into transaction balance.
  $result = $balance + $amount;
  $transaction
    ->get($settings['balance'])
    ->setValue($result);

  // Reflect balance on the target entity.
  $target_entity = $transaction
    ->getTargetEntity();
  if (isset($settings['target_balance']) && $target_entity
    ->hasField($settings['target_balance'])) {
    $target_entity
      ->get($settings['target_balance'])
      ->setValue($result);

    // Set the property indicating that the target entity was updated on
    // execution.
    $transaction
      ->setProperty(TransactionInterface::PROPERTY_TARGET_ENTITY_UPDATED, TRUE);
  }
  return TRUE;
}