Completed
Branch v4.x (236e76)
by Dmitry
40:20 queued 32s
created

AbstractService::getServiceName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
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 25
24
    public function __construct(
25
        string $serviceName,
26
        \Gladyshev\Yandex\Direct\CredentialsInterface $credentials,
27
        \Psr\Http\Client\ClientInterface $httpClient
28 25
    ) {
29 25
        $this->serviceName = $serviceName;
30 25
        $this->credentials = $credentials;
31 25
        $this->httpClient = $httpClient;
32
    }
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
        $result = json_decode($response->getBody()->getContents(), true);
113
114
        /* Handle error response */
115
116
        if (isset($result['error']) && $result['error']) {
117
            throw new \Gladyshev\Yandex\Direct\Exception\ErrorResponseException(
118
                $result['error']['error_string'],
119
                $result['error']['error_detail'],
120
                (int) $result['error']['error_code'],
121
                $request,
122
                $response
123
            );
124
        }
125
126
        $requestId = current($response->getHeader('RequestId'));
127
128
        [$debit, $rest, $limit] = explode('/', current($response->getHeader('Units')));
0 ignored issues
show
Bug introduced by
The variable $debit does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $rest does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $limit does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
129
130
        return [
131
            'request_id' => $requestId,
132
            'units' => [
133
                'debit' => $debit,
134
                'rest' => $rest,
135
                'limit' => $limit
136
            ],
137
            'result' => $result
138
        ];
139
    }
140
}
141