Passed
Branch v4.x (372b59)
by Dmitry
09:30
created

AbstractService   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 143
Duplicated Lines 0 %

Test Coverage

Coverage 9.09%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 58
c 1
b 0
f 0
dl 0
loc 143
ccs 5
cts 55
cp 0.0909
rs 10
wmc 14

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A getServiceName() 0 3 1
A getCredentials() 0 3 1
A call() 0 12 1
A getBody() 0 9 2
A getUri() 0 3 1
A getHeaders() 0 17 4
A handleResponse() 0 42 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gladyshev\Yandex\Direct;
6
7
abstract class AbstractService implements ServiceInterface
8
{
9
    /**
10
     * @var string
11
     */
12
    private $serviceName;
13
14
    /**
15
     * @var \Gladyshev\Yandex\Direct\CredentialsInterface
16
     */
17
    private $credentials;
18
19
    /**
20
     * @var \Psr\Http\Client\ClientInterface
21
     */
22
    private $httpClient;
23
24 54
    public function __construct(
25
        string $serviceName,
26
        \Gladyshev\Yandex\Direct\CredentialsInterface $credentials,
27
        \Psr\Http\Client\ClientInterface $httpClient
28
    ) {
29 54
        $this->serviceName = $serviceName;
30 54
        $this->credentials = $credentials;
31 54
        $this->httpClient = $httpClient;
32 54
    }
33
34
    public function call(array $params = []): array
35
    {
36
        $request = new \GuzzleHttp\Psr7\Request(
37
            'POST',
38
            $this->getUri(),
39
            $this->getHeaders(),
40
            $this->getBody($params)
41
        );
42
43
        $response = $this->httpClient->sendRequest($request);
44
45
        return $this->handleResponse($request, $response);
46
    }
47
48
    protected function getServiceName(): string
49
    {
50
        return $this->serviceName;
51
    }
52
53
    protected function getCredentials(): \Gladyshev\Yandex\Direct\CredentialsInterface
54
    {
55
        return $this->credentials;
56
    }
57
58
    /**
59
     * @return string
60
     */
61
    protected function getUri(): string
62
    {
63
        return $this->getCredentials()->getBaseUrl() . '/json/v5/' . mb_strtolower($this->getServiceName());
64
    }
65
66
    /**
67
     * @return array
68
     */
69
    protected function getHeaders(): array
70
    {
71
        $headers = [
72
            'Content-Type' => 'application/json; charset=utf-8',
73
            'Accept' => 'application/json',
74
            'Authorization' => 'Bearer ' . $this->getCredentials()->getToken(),
75
            'Accept-Language' => $this->getCredentials()->getLanguage()
76
        ];
77
78
        if ($this->getCredentials()->isAgency()) {
79
            $headers['Use-Operator-Units'] = $this->getCredentials()->getUseOperatorUnits() ? 'true' : 'false';
80
            if ($this->getCredentials()->getClientLogin()) {
81
                $headers['Client-Login'] = $this->getCredentials()->getClientLogin();
82
            }
83
        }
84
85
        return $headers;
86
    }
87
88
    /**
89
     * @param array $params
90
     * @return string
91
     */
92
    protected function getBody(array $params): string
93
    {
94
        if (empty($params['params'])) {
95
            $params = new \StdClass();
96
        } else {
97
            $params['params'] = array_filter($params['params']);
98
        }
99
100
        return json_encode($params);
101
    }
102
103
    /**
104
     * @param \Psr\Http\Message\RequestInterface $request
105
     * @param \Psr\Http\Message\ResponseInterface $response
106
     * @return array
107
     */
108
    protected function handleResponse(
109
        \Psr\Http\Message\RequestInterface $request,
110
        \Psr\Http\Message\ResponseInterface $response
111
    ): array {
112
        $contents = $response->getBody()->getContents();
113
        $parsedBody = json_decode($contents, true);
114
115
        if (!is_array($parsedBody)) {
116
            throw new \Gladyshev\Yandex\Direct\Exception\ErrorResponseException(
117
                'Unexpected API response.',
118
                $contents,
119
                0,
120
                $request,
121
                $response
122
            );
123
        }
124
125
        if (!empty($parsedBody['error'])) {
126
            throw new \Gladyshev\Yandex\Direct\Exception\ErrorResponseException(
127
                $parsedBody['error']['error_string'],
128
                $parsedBody['error']['error_detail'],
129
                (int) $parsedBody['error']['error_code'],
130
                $request,
131
                $response
132
            );
133
        }
134
135
        $unitsUsedLogin = current($response->getHeader('Units-Used-Login'));
136
137
        $requestId = current($response->getHeader('RequestId'));
138
139
        [$debit, $rest, $limit] = explode('/', current($response->getHeader('Units')));
140
141
        return [
142
            'request_id' => $requestId,
143
            'units' => [
144
                'debit' => $debit,
145
                'rest' => $rest,
146
                'limit' => $limit
147
            ],
148
            'units_used_login' => $unitsUsedLogin,
149
            'result' => $parsedBody['result'] ?? $parsedBody
150
        ];
151
    }
152
}
153