Emits the before send event for a request and emits an error
event if an error is encountered during the before send.

@param TransactionInterface $transaction

@throws RequestException
491091
public static function emitBefore(TransactionInterface $transaction)
    {
        $request = $transaction->getRequest();
        try {
            $request->getEmitter()->emit(
                'before',
                new BeforeEvent($transaction)
            );
        } catch (RequestException $e) {
            // When a RequestException has been emitted through emitError, the
            // exception is marked as "emitted". This means that the exception
            // had a chance to be rescued but was not. In this case, this method
            // must not emit the error again, but rather throw the exception.
            // This prevents RequestExceptions encountered during the before
            // event from being emitted to listeners twice.
            if ($e->emittedError()) {
                throw $e;
            }
            self::emitError($transaction, $e);
        } catch (\Exception $e) {
            self::emitError($transaction, $e);
        }
    }
978387
public void execute(TransactionCommon t) throws Throwable
    {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.entry(tc, "execute", t);

      _aiStream.removeCompletedPrefix(
        t,
        _messageProcessor.getMessageStore().getUniqueLockID(AbstractItem.STORE_NEVER));
      synchronized (_persistentStreamState)
      {
        if (_streamStateRemoveNeedsToWait)
        {
          _persistentStreamState.wait();
        }

        long lockID = _messageProcessor.getMessageStore().getUniqueLockID(AbstractItem.STORE_NEVER);
        _persistentStreamState.lockItemIfAvailable(lockID);
        Transaction msTran = _messageProcessor.resolveAndEnlistMsgStoreTransaction(t);
        _persistentStreamState.remove(msTran, lockID);
      }

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.exit(tc, "execute");
    }
453664
public function execute(TransactionData $transactionData, $argument = null)
    {
        $this->requestsStorage->addRequest($transactionData->getRequest());
    }
983684
private function _submitTransaction($transaction, $txnType, $clientTransactionId = null)
    {
        $options = array();
        if ($clientTransactionId !== null) {
            $options['clientTransactionId'] = $clientTransactionId;
        }
        $rsp = $this->doRequest($transaction, $options);
        HpsGatewayResponseValidation::checkResponse($rsp, $txnType);
        $response = HpsCheckResponse::fromDict($rsp, $txnType);

        if ($response->responseCode != 0) {
            throw new HpsCheckException(
                $rsp->Header->GatewayTxnId,
                $response->details,
                $response->responseCode,
                $response->responseText
            );
        }

        return $response;
    }
909939
public synchronized void prepare(Transaction transaction)
                    throws ObjectManagerException
    {
        throw new InvalidStateException(this, InternalTransaction.stateTerminated, InternalTransaction.stateNames[InternalTransaction.stateTerminated]);
    }
318199
public function execute(TransactionData $transactionData, $argument = null)
    {
        $transactionData->setResponse(
            $this->processAndGetResponse(
                $transactionData,
                function (TransactionData $transaction, Expectation $expectation) {
                    $this->validateRequestOrThrowException($expectation, $this->logger);
                    $executions = $this->searchForExecutionsCount($expectation);
                    $this->logger->debug('Listed ' . \count($executions) . ' request matching the expectation');

                    return $transaction->getResponse()
                        ->withStatus(200)
                        ->withHeader('Content-Type', 'application/json')
                        ->withBody(new StringStream(json_encode($executions)));
                }
            )
        );
    }
783165
public function beginTransaction()
    {
        if (self::$transaction) {
            throw new TransactionException("Transaction Already Started");
        }

        self::$transaction = true;
        foreach (self::$connectionList as $dbDriver) {
            $dbDriver->beginTransaction();
        }
    }
520677
public function afterCommit(TransactionEvent $event) {
    if ($event->getPhase() == TransactionEvent::AFTER_COMMIT) {
      $response = $this->getResponse();
      $locationOid = $response->getHeader('Location');

      // replace changed oids
      $changedOids = $event->getInsertedOids();
      foreach ($changedOids as $oldOid => $newOid) {
        if ($response->hasValue($oldOid)) {
          $value = $response->getValue($oldOid);
          $response->setValue($newOid, $value);
          $response->clearValue($oldOid);
        }
        if ($locationOid == $oldOid) {
          $this->setLocationHeaderFromOid($newOid);
        }
      }
    }
  }
816504
private function _submitTransaction($transaction, $txnType)
    {

        try {
            $response = $this->doRequest($transaction);
        } catch (HpsException $e) {
            if ($e->innerException != null && $e->innerException->getMessage() == 'gateway_time-out') {
                throw new HpsException('An error occurred and the gateway has timed out', 'gateway_timeout', $e, 'gateway_timeout');
            }
            throw $e;
        }

        $this->_processGatewayResponse($response, $txnType);

        $rvalue = null;
        switch ($txnType) {
            case 'GetAttachments':
                $rvalue = HpsAttachment::fromDict($response, $txnType);
                break;
            default:
                break;
        }

        return $rvalue;
    }
1095557
public function handleVersionTwo(Transaction $transaction): Transaction
    {
        $transaction->id = Hash::sha256($transaction->serialize())->getHex();

        return $transaction;
    }
1062836
public function flush( $transaction = null, $onFailure = self::FLUSH_ABORT, $throwExceptions = true )
    {

        if( is_null( $transaction ) ) {
            $transaction = self::TRANSACTIONS_ALL;
        }

        if( is_null( $onFailure) ) {
            $onFailure = self::FLUSH_ABORT;
        }

        $response = new Response();
        $exceptions = [];
        $haveAnyTransactionsFailed = false;

        // simulate
        $simulate = ( $this->debug & self::DEBUG_SIMULATE );

        // profiler
        $profiler = new Profiler( "Record manager" );
        $profiler->log();

        // debugging query show
        $debugQuery = null;
        if( $this->debug & self::DEBUG_SHOW_QUERY ) {
            $debugQuery = function ( $e, $event, $data ) {
                echo $data . "\n";
            };
            $this->db->debug->on( Debug::INFO, $debugQuery );
        }

        // trap all throw exceptions so that we can properly unattach the $db->debug->on( Pg::QueryPassed $listener )
        try {

            // iterate selected transactions
            foreach( $this->getQueue( $transaction, true, true ) as $transaction => $queue ) {

                unset( $this->queue[$transaction] );

                $taskResponse = null;
                $hasTransactionFailed = false;

                $beginTransaction = new Query( "BEGIN TRANSACTION READ WRITE; /* %transaction:% */" );
                $beginTransaction->transaction = $transaction;
                $this->db->query( $beginTransaction );

                $this->eventEmitter->emit( EventEmitter::TRANSACTION_START, $this, $transaction, $queue );

                // loop over our tasks
                foreach( $queue as $task ) {

                    // are we continuing to process?
                    if( $hasTransactionFailed or ( $haveAnyTransactionsFailed && $onFailure === self::FLUSH_ABORT ) ) {
                        $taskResponse = Response::ABORTED;
                    } else {
                        try {
                            $taskResponse = $task->execute( $this->db, $simulate ) ? Response::SUCCESS : Response::FAILED;
                        } catch( \Exception $e ) {
                            // It'd be nice if we could just test for Query exceptions here but unfortunately PHPUnit dicks pretty hard with exception types.
                            // @Mr Beale. I realise this violates the "only handle exceptions that you understand" rule but I can't find a way round this. Pete
                            $taskResponse = $e;
                            $exceptions[] = $e;
                        }
                    }

                    // transaction success
                    if( $taskResponse !== Response::SUCCESS ) {
                        $hasTransactionFailed = true;
                        $haveAnyTransactionsFailed = true;
                    }

                    $response->add( $transaction, $task, $taskResponse );

                }

                // end or rollback transaction
                $endTransaction = new Query( "%commitOrRollback:% TRANSACTION; /* %transaction:% */" );
                $endTransaction->commitOrRollback = new Raw($hasTransactionFailed ? 'ROLLBACK' : 'COMMIT');
                $endTransaction->transaction = $transaction;
                $this->db->query( $endTransaction );

                // response rollback
                if( $hasTransactionFailed ) {
                    $response->rollback( $transaction );
                }

                $profiler->log( $transaction );

            }

            // if we've gathered any exceptions throw them here
            if( $throwExceptions and $exceptions ) {
                throw $exceptions[0];
            }

            $response->profilerAssign( $profiler );

        } catch ( \Exception $e ) {
            $this->db->debug->removeListener( Pg::QUERY_PARSED, $debugQuery );
            throw $e;
        }

        return $response;

    }
421478
protected function _beforeCall( string $url, string $requestHash )
	{
		foreach ($this->beforeCall as $function)
		{
			if ($function($this, $url, $requestHash) === false)
			{
				throw new RequestException("Request terminated by beforeCall function.");
			}
		}
	}
1301608
public function register(Transaction $transaction)
    {
        $name = $transaction->getTransactionName();

        // Do not override the
        if (isset($this->store[$name]) === true) {
            throw new DuplicateTransactionNameException($name);
        }

        // Push to Store
        $this->store[$name] = $transaction;
    }
1002724
public function update(Transaction $transaction, UpdateTransactionRequest $request)
    {
        $this->transaction->update($transaction, $request->all());

        return redirect()->route('admin.order.order.show', $transaction->order_id)
            ->withSuccess(trans('core::core.messages.resource updated', ['name' => trans('order::transactions.title.transactions')]));
    }
398427
protected function validateTransaction(Transaction $transaction)
    {
        if (!$transaction->getParent() && in_array($transaction->getType()->getValue(), array(Transaction\TransactionType::CAPTURE, Transaction\TransactionType::REFUND, Transaction\TransactionType::VOID))) {
            throw ValidationException::parentTransactionRequired();
        }

        $credentials = $transaction->getCredentials();

        if (!$credentials) {
            throw ValidationException::missingCredentials();
        } elseif (null === $credentials->getCredential('username') || null === $credentials->getCredential('password')) {
            throw ValidationException::missingRequiredParameter('username or password');
        }

        $account = $transaction->getAccount();

        if (!$account) {
            throw ValidationException::missingAccountInformation();
        }

        if ((!($account instanceof CardAccount) && !($account instanceof SwipedCardAccount))
            || (!($account instanceof SwipedCardAccount) && $transaction->getNetwork() == Transaction\NetworkType::SWIPED)
        ) {
            throw ValidationException::invalidAccountType($account);
        }

        if (!$account instanceof SwipedCardAccount) {
            if (null === $account->getAccountNumber()) {
                throw ValidationException::missingRequiredParameter('account number');
            } elseif (null === $account->getExpMonth() || null === $account->getExpYear()) {
                throw ValidationException::missingRequiredParameter('card expiration');
            }
        }
    }
15569
protected function handleQueryResponse(Transaction $transaction, $data)
    {
        $result = $transaction->getResult();
        $parentResult = $transaction->getParent()->getResult();
        $eventResult = null;

        foreach ($data->Results as $event) {
            if ($event->TransAct_ReferenceID === $parentResult->getExternalId()) {
                $eventResult = $event;

                // We don't break in case the transaction has multiple events in the same query-- we want the latest
            }
        }

        $resultType = $parentResult->getStatus()->getValue();

        if (null !== $eventResult) {
            switch ($eventResult->ResultingStatus) {
                case 'Scheduled':
                    $resultType = Result\ResultStatus::PENDING;
                    break;

                case 'Cancelled':
                    $resultType = Result\ResultStatus::CANCELLED;
                    break;

                case 'In-Process':
                    $resultType = Result\ResultStatus::PROCESSED;
                    break;

                case 'Cleared':
                    $resultType = Result\ResultStatus::APPROVED;
                    break;

                case 'Failed Verification':
                case 'Returned-NSF':
                case 'Returned-Other':
                    $resultType = Result\ResultStatus::DECLINED;
                    break;

                case 'Charged Back':
                    $resultType = Result\ResultStatus::CHARGED_BACK;
                    break;

                case 'Merchant Hold':
                case 'Processor Hold':
                    $resultType = Result\ResultStatus::HOLD;
                    break;
            }
        }

        $result->setStatus(new Result\ResultStatus($resultType));
    }
639942
public function _send($transaction)
        {
            $storeId        = $this->getConfigData('store_id');
            $apiToken       = $this->getConfigData('api_token');

            $request        = new mpgRequest($transaction);

            $mpgHttpsPost   = new mpgHttpsPost($storeId, $apiToken, $request);

            return $mpgHttpsPost->getMpgResponse();
        }