Client   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 171
Duplicated Lines 8.77 %

Coupling/Cohesion

Components 2
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 15
loc 171
ccs 0
cts 59
cp 0
rs 10
c 0
b 0
f 0
wmc 13
lcom 2
cbo 7

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 7 7 1
A make() 0 11 1
A getSerialNumber() 0 6 1
A init() 8 8 1
A payment() 0 4 1
A getState() 0 4 1
A payout() 0 14 5
A makeRequest() 0 12 1
A getSecretData() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php declare(strict_types=1);
2
3
namespace Personnage\Tinkoff\SDK\E2Card;
4
5
use Closure;
6
use GuzzleHttp\Psr7\Request;
7
use Personnage\Tinkoff\SDK\Exception\HttpException;
8
use Personnage\Tinkoff\SDK\Exception\ResponseException;
9
use Personnage\Tinkoff\SDK\HasSender;
10
use Personnage\Tinkoff\SDK\Response\Init;
11
use Personnage\Tinkoff\SDK\Response\Payment;
12
use Personnage\Tinkoff\SDK\Response\State;
13
use Personnage\Tinkoff\SDK\SecretDataContainer;
14
use Personnage\Tinkoff\SDK\Sender;
15
use Psr\Http\Message\RequestInterface;
16
17
final class Client
18
{
19
    use HasSignature, HasSender;
20
21
    private $baseUri;
22
    private $terminalKey;
23
    private $signer;
24
25
    /**
26
     * @var array
27
     */
28
    private static $requestHeaders = [
29
        'Accept' => 'application/json',
30
        'Content-Type' => 'application/x-www-form-urlencoded',
31
    ];
32
33
    /**
34
     * Init a new instance.
35
     *
36
     * @param string  $uri
37
     * @param string  $terminalKey
38
     * @param Closure $signer
39
     * @param Sender  $sender
40
     */
41 View Code Duplication
    public function __construct(string $uri, string $terminalKey, Closure $signer, Sender $sender)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
42
    {
43
        $this->baseUri     = rtrim($uri, '/');
44
        $this->terminalKey = $terminalKey;
45
        $this->signer      = $signer;
46
        $this->setSender($sender);
47
    }
48
49
    /**
50
     * Create a new instance.
51
     *
52
     * @param string   $uri
53
     * @param string   $terminalKey
54
     * @param string   $pemFile
55
     * @param Sender   $sender
56
     * @return self
57
     */
58
    public static function make(string $uri, string $terminalKey, string $pemFile, Sender $sender): self
59
    {
60
        $signer = function (string $raw) use ($pemFile): SecretDataContainer {
61
            $cert = realpath($pemFile);
62
            $digest = self::digest($raw);
63
64
            return new SecretDataContainer(self::getSerialNumber($cert), $digest, self::sign($digest, $cert));
65
        };
66
67
        return new self($uri, $terminalKey, $signer, $sender);
68
    }
69
70
    /**
71
     * Get serial number of X509.
72
     *
73
     * @param  string  $pemFile
74
     * @return string
75
     */
76
    private static function getSerialNumber(string $pemFile): string
77
    {
78
        $text = openssl_x509_parse('file://'.$pemFile, true);
79
80
        return $text['serialNumber'];
81
    }
82
83
    /**
84
     * Init a new payment session.
85
     *
86
     * @param string $orderId Номер заказа в системе Продавца.
87
     * @param string $cardId  Идентификатор карты пополнения.
88
     * @param int    $amount  Сумма в копейках.
89
     * @param array  $extra   Массив дополнительных полей, которые могут быть переданы в этом запросе.
90
     *
91
     * @return Init
92
     * @throws HttpException
93
     */
94 View Code Duplication
    public function init(string $orderId, string $cardId, int $amount, array $extra = []): Init
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
    {
96
        $extra['Amount'] = $amount;
97
        $extra['CardId'] = $cardId;
98
        $extra['OrderId'] = $orderId;
99
100
        return new Init($this->send($this->makeRequest('Init', $extra)));
101
    }
102
103
    /**
104
     * Make payout to card.
105
     *
106
     * @param mixed $paymentId
107
     *
108
     * @return Payment
109
     * @throws HttpException
110
     */
111
    public function payment($paymentId): Payment
112
    {
113
        return new Payment($this->send($this->makeRequest('Payment', ['PaymentId' => $paymentId])));
114
    }
115
116
    /**
117
     * Get op state.
118
     *
119
     * @param mixed $paymentId
120
     *
121
     * @return State
122
     * @throws HttpException
123
     */
124
    public function getState($paymentId): State
125
    {
126
        return new State($this->send($this->makeRequest('GetState', ['PaymentId' => $paymentId])));
127
    }
128
129
    /**
130
     * Init a new payment session and make payout to card.
131
     *
132
     * @param string $orderId Номер заказа в системе Продавца.
133
     * @param string $cardId  Идентификатор карты пополнения.
134
     * @param int    $amount  Сумма в копейках.
135
     * @param array  $extra   Массив дополнительных полей, которые могут быть переданы в этом запросе.
136
     *
137
     * @return Payment
138
     * @throws HttpException
139
     * @throws ResponseException
140
     */
141
    public function payout(string $orderId, string $cardId, int $amount, array $extra = []): Payment
142
    {
143
        $response = $this->init($orderId, $cardId, $amount, $extra);
144
        if ($response->hasError() || 'CHECKED' !== $response->getStatus()) {
145
            throw new ResponseException($response);
146
        }
147
148
        $response = $this->payment($response->getPaymentId());
149
        if ($response->hasError() || 'COMPLETED' !== $response->getStatus()) {
150
            throw new ResponseException($response);
151
        }
152
153
        return $response;
154
    }
155
156
    /**
157
     * Make a new http request.
158
     *
159
     * @param string $uri
160
     * @param array  $body
161
     *
162
     * @return RequestInterface
163
     */
164
    private function makeRequest(string $uri, array $body = []): RequestInterface
165
    {
166
        // Append terminal key
167
        $body['TerminalKey'] = $this->terminalKey;
168
169
        $data = $this->getSecretData($body);
170
        $body['DigestValue'] = base64_encode($data->getDigest());
171
        $body['SignatureValue'] = base64_encode($data->getSignature());
172
        $body['X509SerialNumber'] = $data->getSerial();
173
174
        return new Request('post', "$this->baseUri/$uri", self::$requestHeaders, http_build_query($body, '', '&'));
175
    }
176
177
    /**
178
     * Get digest and signature for request data.
179
     *
180
     * @param  array  $body
181
     * @return SecretDataContainer
182
     */
183
    private function getSecretData(array $body): SecretDataContainer
184
    {
185
        return \call_user_func($this->signer, self::getValues($body));
186
    }
187
}
188