Failed Conditions
Push — master ( d14540...c934fa )
by Sylvain
09:16
created

BankingInfos::qrBill()   B

Complexity

Conditions 9
Paths 2

Size

Total Lines 70
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
eloc 45
c 0
b 0
f 0
dl 0
loc 70
ccs 0
cts 39
cp 0
rs 7.6444
cc 9
nc 2
nop 5
crap 90

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Api\Field\Query;
6
7
use Application\Model\User;
8
use Ecodev\Felix\Api\Field\FieldInterface;
9
use Ecodev\Felix\Service\Bvr;
10
use GraphQL\Type\Definition\Type;
11
use Laminas\Http\Client;
12
use Laminas\Http\Client\Exception\RuntimeException;
13
use Laminas\Http\Request;
14
use Laminas\Http\Response;
15
16
abstract class BankingInfos implements FieldInterface
17
{
18 1
    public static function build(): array
19
    {
20
        return
21
            [
22 1
                'name' => 'bankingInfos',
23 1
                'type' => Type::nonNull(_types()->get('BankingInfos')),
24 1
                'description' => 'Info to top-up the current user account by bank transfer',
25
                'args' => [
26 1
                    'user' => Type::nonNull(_types()->getId(User::class)),
27 1
                    'amount' => _types()->get('Money'),
28
                ],
29 1
                'resolve' => function ($root, array $args): array {
30
                    global $container;
31
                    $config = $container->get('config');
32
                    $banking = $config['banking'];
33
                    $iban = $banking['iban'];
34
                    $paymentTo = $banking['paymentTo'];
35
                    $paymentFor = $banking['paymentFor'];
36
37
                    $user = $args['user']->getEntity();
38
                    $amount = $args['amount'] ?? null;
39
40
                    $referenceNumber = Bvr::getReferenceNumber('000000', (string) $user->getId());
41
42
                    $result = [
43
                        'iban' => $iban,
44
                        'paymentTo' => $paymentTo,
45
                        'paymentFor' => $paymentFor,
46
                        'referenceNumber' => $referenceNumber,
47
                    ];
48
49
                    $qrCodeField = self::qrBill($user, $amount, $iban, $paymentFor, false);
50
                    $qrBillField = self::qrBill($user, $amount, $iban, $paymentFor, true);
51
                    $result = array_merge($result, $qrCodeField, $qrBillField);
52
53
                    return $result;
54 1
                },
55
            ];
56
    }
57
58
    /**
59
     * Lazy resolve qrBill or qrCode fields for banking infos query
60
     *
61
     * @param mixed $amount
62
     * @param mixed $iban
63
     * @param mixed $paymentFor
64
     */
65
    protected static function qrBill(User $user, $amount, $iban, $paymentFor, bool $paymentPart): array
66
    {
67
        $resolve = function () use ($user, $amount, $iban, $paymentFor, $paymentPart): ?string {
68
            global $container;
69
70
            if (!Bvr::isQrIban($iban)) {
71
                return null;
72
            }
73
74
            $config = $container->get('config');
75
            $request = new Request();
76
            $request->setUri('https://qrbill.ecodev.ch/qr-code');
77
            $request->getHeaders()->addHeaders([
78
                'Content-Type' => 'application/json',
79
                'Accept' => $paymentPart ? 'application/json application/pdf' : 'application/json image/svg+xml',
80
                'Referer' => 'https://' . $config['hostname'],
81
            ]);
82
            $request->setMethod(Request::METHOD_POST);
83
84
            $creditorLines = explode("\n", $paymentFor);
85
            $creditor = [
86
                'name' => $creditorLines[0],
87
            ];
88
            if (count($creditorLines) > 2) {
89
                $creditor['addressLine1'] = $creditorLines[1];
90
                $creditor['addressLine2'] = $creditorLines[2];
91
            } else {
92
                $creditor['addressLine2'] = $creditorLines[1];
93
            }
94
95
            $attrs = [
96
                'creditor' => $creditor,
97
                'customerIdentification' => null,
98
                'referenceNumber' => (string) $user->getId(),
99
                'iban' => $iban,
100
                'amount' => $amount,
101
            ];
102
103
            if (!empty($user->getPostcode()) && !empty($user->getLocality())) {
104
                $debtor = [
105
                    'name' => $user->getName(),
106
                    'addressLine2' => implode(' ', array_filter([$user->getPostcode(), $user->getLocality()])),
107
                ];
108
                $attrs['ultimateDebtor'] = $debtor;
109
            }
110
111
            $request->setContent(json_encode($attrs));
112
            $client = new Client();
113
114
            try {
115
                /** @var Response $response */
116
                $response = $client->dispatch($request);
117
                if (!$response->isSuccess()) {
118
                    _log()->err('Erreur de génération du QR code: ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase());
119
120
                    return null;
121
                }
122
            } catch (RuntimeException $e) {
123
                _log()->err($e->getMessage(), $attrs);
124
125
                return null;
126
            }
127
128
            $content = json_decode($response->getBody());
129
130
            return $content->qrcode;
131
        };
132
133
        return [
134
            $paymentPart ? 'qrBill' : 'qrCode' => $resolve,
135
        ];
136
    }
137
}
138