ApiClient::execute()   A
last analyzed

Complexity

Conditions 4
Paths 32

Size

Total Lines 55
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 55
ccs 30
cts 30
cp 1
rs 9.078
c 0
b 0
f 0
cc 4
eloc 31
nc 32
nop 1
crap 4

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
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 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 9
    public function __construct(
38
        Interfaces\Configuration $configuration,
39
        \Psr\Log\LoggerInterface $logger
40
    ) {
41 9
        $this->uniqueId = $this->getUniqueId();
42 9
        $this->logger   = $logger;
43
44 9
        $this->setConfiguration($configuration);
45 9
    }
46
47
    /**
48
     * @param $client
49
     * @return ApiClient
50
     */
51 5
    public function setClient($client)
52
    {
53 5
        $this->client = $client;
54 5
        return $this;
55
    }
56
57
    /**
58
     * @return string
59
     */
60 9
    public function getUniqueId()
61
    {
62 9
        if (!$this->uniqueId) {
63 9
            $this->uniqueId = uniqid();
64 9
        }
65
66 9
        return $this->uniqueId;
67
    }
68
69
    /**
70
     * @param string $uniqueId
71
     * @return ApiClient
72
     */
73 5
    public function setUniqueId($uniqueId)
74
    {
75 5
        $this->uniqueId = $uniqueId;
76 5
        return $this;
77
    }
78
79
    /**
80
     * @return \GuzzleHttp\Client
81
     */
82 7
    public function getClient()
83
    {
84 7
        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 7
        return $this->client;
107
    }
108
109
    /**
110
     * @param Interfaces\Context $context
111
     * @return void
112
     */
113 4
    public function execute(Interfaces\Context $context)
114
    {
115
        try {
116 4
            $configuration = $this->getConfiguration();
117 4
            $contextUrl    = $context->getUrl();
118 4
            $url           = $contextUrl->getFullUrl();
119
120
            $options       = [
121
                'headers' => [
122 4
                    'access-token' => $configuration->getAccessToken(),
123 4
                    'user-key'     => $configuration->getUserKey()
124 4
                ],
125
                'exceptions' => false
126 4
            ];
127
128 4
            if (strtolower($context->getHttpMethod()) === 'get') {
129
130
                // send context on query string
131 1
                $options['query'] = $context->exportContextData();
132 1
            } else {
133
134
                // send context on request body as JSON 
135 3
                $options['body'] = json_encode($context->exportContextData());
136
            }
137
138 4
            $this->logRequest($url, $options, $context->getHttpMethod());
139
140 4
            $response = $this->getClient()
141 4
                ->{$context->getHttpMethod()}($url, $options);
142
143 3
            $this->checkResponse($response);
144 2
            $this->logResponse($response);
145
146 2
            return $response;
147
148 2
        } catch (\Exception $e) {
149
150 2
            $message = "Unable to execute context {$context->getName()}" .
151 2
                " ( Exception message: {$e->getMessage()})";
152
153 2
            $this->logger->error($message, $context->exportContextData());
154
155 2
            $retryMessage = sprintf('Try Again - Message: %s - Code: %s', $e->getMessage(), $e->getCode());
156 2
            $code = 500;
157
158 2
            if ($e instanceof \GuzzleHttp\Exception\RequestException) {
159 1
                $this->logResponse($e->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $e->getResponse() can be null; however, logResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
160
161 1
                $retryMessage = $e->getResponse()->getBody();
162 1
                $code         = $e->getResponse()->getStatusCode();
163 1
            }
164
165 2
            throw new Exceptions\RetryMessage($retryMessage, $code);
166
        }
167
    }
168
169
    /**
170
     * @param string $url
171
     * @param array $options
172
     * @param string $method
173
     * @return void
174
     */
175 4
    private function logRequest($url, $options, $method = '')
176
    {
177 4
        $baseUri = $this->getClient()->getConfig('base_uri');
178
179 4
        $url = $baseUri . $url;
180
181 4
        $message = sprintf(
182 4
            '%s %s REQUEST TO: %s -- OPTIONS %s',
183 4
            $this->getUniqueId(),
184 4
            $method,
185 4
            $url,
186 4
            json_encode($options)
187 4
        );
188
189 4
        $this->logger->info($message);
190 4
    }
191
192
    /**
193
     * @param \Psr\Http\Message\ResponseInterface $response
194
     * @return void
195
     */
196 3
    private function logResponse(
197
        \Psr\Http\Message\ResponseInterface $response
198
    ) {
199 3
        $message = sprintf(
200 3
            '%s RESPONSE: -- HTTP CODE %s -- BODY %s',
201 3
            $this->getUniqueId(),
202 3
            $response->getStatusCode(),
203 3
            $response->getBody()
204 3
        );
205
206 3
        $this->logger->info($message);
207 3
    }
208
209
    /**
210
     * @param \Psr\Http\Message\ResponseInterface $response
211
     * @return bool
212
     */
213 3
    private function checkResponse(
214
        \Psr\Http\Message\ResponseInterface $response
215
    ) {
216 3
        if (!in_array(
217 3
            $response->getStatusCode(),
218 3
            array(static::RESPONSE_OK, static::RESPONSE_OK_NO_BODY)
219 3
        )) {
220 1
            throw new Exceptions\RetryMessage(
221 1
                $response->getBody(),
222 1
                $response->getStatusCode()
223 1
            );
224
        }
225 2
    }
226
227
    /**
228
     * Gets the value of configuration
229
     *
230
     * @return Interfaces\Configuration
231
     */
232 6
    public function getConfiguration()
233
    {
234 6
        return $this->configuration;
235
    }
236
237
    /**
238
     * Sets the value of Configuration
239
     *
240
     * @param Interfaces\Configuration $configuration
241
     * @return ApiClient
242
     */
243 9
    public function setConfiguration(Interfaces\Configuration $configuration)
244
    {
245 9
        $this->configuration = $configuration;
246 9
        return $this;
247
    }
248
}
249