Passed
Push — master ( 01baf6...9ed857 )
by Vitor de
04:10
created

ApiClient::execute()   B

Complexity

Conditions 3
Paths 17

Size

Total Lines 45
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 45
ccs 27
cts 27
cp 1
rs 8.8571
cc 3
eloc 27
nc 17
nop 1
crap 3
1
<?php
2
3
namespace GFG\Hek;
4
5
use GuzzleHttp\Client as HttpClient;
6
use GuzzleHttp\Exception\RequestException;
7
8
class ApiClient
9
{
10
    const RESPONSE_OK         = 200;
11
    const RESPONSE_OK_NO_BODY = 204;
12
13
    /**
14
     * @var \GuzzleHttp\Client
15
     */
16
    private $client;
17
18
    /**
19
     * @var string
20
     */
21
    private $uniqueId;
22
23
    /**
24
     * @var \Hek\Interfaces\Configuration
25
     */
26
    private $configuration;
27
28
    /**
29
     * @var \Psr\Log\LoggerInterface
30
     */
31
    private $logger;
32
33
    /**
34
     * @param Interfaces\Configuration $configuration
35
     * @param \Psr\Log\LoggerInterface $logger
36
     */
37 8
    public function __construct(
38
        Interfaces\Configuration $configuration,
39
        \Psr\Log\LoggerInterface $logger
40
    ) {
41 8
        $this->uniqueId = $this->getUniqueId();
42 8
        $this->logger   = $logger;
43
44 8
        $this->setConfiguration($configuration);
45 8
    }
46
47
    /**
48
     * @param $client
49
     * @return Client
50
     */
51 4
    public function setClient($client)
52
    {
53 4
        $this->client = $client;
54 4
        return $this;
55
    }
56
57
    /**
58
     * @return string
59
     */
60 8
    public function getUniqueId()
61
    {
62 8
        if (!$this->uniqueId) {
63 8
            $this->uniqueId = uniqid();
64 8
        }
65
66 8
        return $this->uniqueId;
67
    }
68
69
    /**
70
     * @param string $uniqueId
71
     * @return Client
72
     */
73 4
    public function setUniqueId($uniqueId)
74
    {
75 4
        $this->uniqueId = $uniqueId;
76 4
        return $this;
77
    }
78
79
    /**
80
     * @return \GuzzleHttp\Client
81
     */
82 6
    public function getClient()
83
    {
84 6
        if (!$this->client) {
85
86
            // http authentication
87 2
            $auth = [];
88 2
            if ($this->getConfiguration()->getHttpUser()) {
89
                $auth = [
90
                    'auth' => [
91 1
                        $this->getConfiguration()->getHttpUser(),
92 1
                        $this->getConfiguration()->getHttpPass()
93 1
                    ]
94 1
                ];
95 1
            }
96
97 2
            $this->client = new HttpClient(array_merge($auth, [
98 2
                'base_uri'  => $this->getConfiguration()->getBaseUrl(),
99
                'headers'   => [
100 2
                    'Accept'       => 'application/json',
101
                    'Content-Type' => 'application/json'
102 2
                ]
103 2
            ]));
104 2
        }
105
106 6
        return $this->client;
107
    }
108
109
    /**
110
     * @param Interfaces\Context $context
111
     * @return void
112
     */
113 3
    public function execute(Interfaces\Context $context)
114
    {
115
        try {
116 3
            $configuration = $this->getConfiguration();
117 3
            $contextUrl    = $context->getUrl();
118 3
            $url           = $contextUrl->getFullUrl();
119
120
            $options       = [
121 3
                'body'    => json_encode($context->exportContextData()),
122
                'headers' => [
123 3
                    'access-token' => $configuration->getAccessToken(),
124 3
                    'user-key'     => $configuration->getUserKey()
125 3
                ],
126
                'exceptions' => false
127 3
            ];
128
129
130 3
            $this->logRequest($url, $options);
131
132 3
            $response = $this->getClient()
133 3
                ->{$context->getHttpMethod()}($url, $options);
134
135 2
            $this->checkResponse($response);
136 1
            $this->logResponse($response);
137
138 3
        } catch (\Exception $e) {
139
140 2
            $message = "Unable to execute context {$context->getName()}" .
141 2
                " ( Exception message: {$e->getMessage()})";
142
143 2
            $this->logger->error($message, $context->exportContextData());
144
145 2
            $retryMessage = 'Try Again';
146 2
            $code = 500;
147
148 2
            if ($e instanceof \GuzzleHttp\Exception\RequestException) {
149 1
                $this->logResponse($e->getResponse());
150
151 1
                $retryMessage = $e->getResponse()->getBody();
152 1
                $code         = $e->getResponse()->getStatusCode();
153 1
            }
154
155 2
            throw new Exceptions\RetryMessage($retryMessage, $code);
156
        }
157 1
    }
158
159
    /**
160
     * @param string $url
161
     * @param array $options
162
     * @return void
163
     */
164 3
    private function logRequest($url, $options)
165
    {
166 3
        $message = sprintf(
167 3
            '%s REQUEST TO: %s -- OPTIONS %s',
168 3
            $this->getUniqueId(),
169 3
            $url,
170 3
            json_encode($options)
171 3
        );
172
173 3
        $this->logger->info($message);
174 3
    }
175
176
    /**
177
     * @param \GuzzleHttp\Message\ResponseInterface $response
178
     * @return void
179
     */
180 2
    private function logResponse(
181
        \Psr\Http\Message\ResponseInterface $response
182
    ) {
183 2
        $message = sprintf(
184 2
            '%s RESPONSE: -- HTTP CODE %s -- BODY %s',
185 2
            $this->getUniqueId(),
186 2
            $response->getStatusCode(),
187 2
            $response->getBody()
188 2
        );
189
190 2
        $this->logger->info($message);
191 2
    }
192
193
    /**
194
     * @param \GuzzleHttp\Message\ResponseInterface $response
195
     * @return bool
196
     */
197 2
    private function checkResponse(
198
        \Psr\Http\Message\ResponseInterface $response
199
    ) {
200 2
        if (!in_array(
201 2
            $response->getStatusCode(),
202 2
            array(static::RESPONSE_OK, static::RESPONSE_OK_NO_BODY)
203 2
        )) {
204 1
            throw new Exceptions\RetryMessage(
205 1
                $response->getBody(),
206 1
                $response->getStatusCode()
207 1
            );
208
        }
209 1
    }
210
211
    /**
212
     * Gets the value of configuration
213
     *
214
     * @return Interfaces\Configuration
215
     */
216 5
    public function getConfiguration()
217
    {
218 5
        return $this->configuration;
219
    }
220
221
    /**
222
     * Sets the value of Configuration
223
     *
224
     * @param Interfaces\Configuration $configuration
225
     * @return Client
226
     */
227 8
    public function setConfiguration(Interfaces\Configuration $configuration)
228
    {
229 8
        $this->configuration = $configuration;
0 ignored issues
show
Documentation Bug introduced by
It seems like $configuration of type object<GFG\Hek\Interfaces\Configuration> is incompatible with the declared type object<Hek\Interfaces\Configuration> of property $configuration.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
230 8
        return $this;
231
    }
232
}
233