Completed
Pull Request — master (#7)
by Stefan
09:04
created

CaptureTransactionAction::supports()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Karser\PayumSaferpay\Action\Api;
4
5
use ArrayAccess;
6
use Karser\PayumSaferpay\Constants;
7
use Karser\PayumSaferpay\Exception\SaferpayHttpException;
8
use Karser\PayumSaferpay\Request\Api\CaptureTransaction;
9
use Payum\Core\Bridge\Spl\ArrayObject;
10
use Payum\Core\Exception\LogicException;
11
use Payum\Core\Exception\RequestNotSupportedException;
12
13
class CaptureTransactionAction extends BaseApiAwareAction
14
{
15 16
    public function execute($request)
16
    {
17 16
        RequestNotSupportedException::assertSupports($this, $request);
18 15
        $model = ArrayObject::ensureArrayObject($request->getModel());
19
20 15
        $status = $model['Transaction']['Status'];
21 15
        if ($status === Constants::STATUS_CAPTURED) {
22 1
            return; //already captured
23
        }
24 14
        if ($status !== Constants::STATUS_AUTHORIZED) {
25 1
            throw new LogicException(sprintf('Cannot capture transaction with status: "%s"', $status));
26
        }
27 13
        if (empty($model['Transaction']['Id'])) {
28 1
            throw new LogicException('Transaction is missing');
29
        }
30
        try {
31 12
            $response = $this->api->captureTransaction($model['Transaction']['Id']);
32 11
            $model->replace(['Transaction' => array_merge($model['Transaction'], [
33 11
                'Status' => $response['Status'],
34 11
                'Date' => $response['Date'],
35
            ])]);
36 1
        } catch (SaferpayHttpException $e) {
37 1
            $error = $e->toArray();
38 1
            $errorName = $error['Data']['ErrorName'] ?? null;
39
            // do not raise any errors if transaction already has been captured
40 12
            if ($errorName !== Constants::ERROR_NAME_TRANSACTION_ALREADY_CAPTURED) {
41
                $model['Error'] = $error;
42 20
                $model->replace(['Transaction' => array_merge($model['Transaction'], ['Status' => Constants::STATUS_FAILED])]);
43
            }
44
        }
45 20
    }
46 20
47
    public function supports($request): bool
48
    {
49
        return
50
            $request instanceof CaptureTransaction &&
51
            $request->getModel() instanceof ArrayAccess;
52
    }
53
}
54