Guzzles::parseJson()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Sarahman\SmsService\Traits;
4
5
use Exception;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Exception\BadResponseException;
8
use GuzzleHttp\Psr7\Response;
9
use Illuminate\Support\Facades\Log;
10
use Psr\Http\Message\ResponseInterface;
11
12
trait Guzzles
13
{
14
    private $baseUri = '';
15
    private $timeout = 0;
16
17
    /**
18
     * Instantiates and returns the Guzzle client.
19
     *
20
     * @return Client
21
     */
22
    private function buildClient()
23
    {
24
        return new Client([
25
            'base_uri'    => $this->baseUri,
26
            'timeout'     => isset($this->timeout) ? $this->timeout : 0,
27
            'http_errors' => false,
28
            'headers'     => [
29
                'Content-Type' => 'application/json',
30
            ],
31
        ]);
32
    }
33
34
    /**
35
     * Executes the guzzle request with given params and handle exception if occurred.
36
     *
37
     * @param Client $client
38
     * @param string $method
39
     * @param string $url
40
     * @param array  $params
41
     *
42
     * @return ResponseInterface $response
43
     */
44
    final protected function makeRequestWithHandlingException(Client $client, $method, $url, array $params = [])
45
    {
46
        try {
47
            $response = $client->{$method}($url, $params);
48
        } catch (BadResponseException $e) {
49
            Log::error($e);
50
            $response = $e->getResponse();
51
        } catch (Exception $e) {
52
            Log::error($e);
53
            $response = new Response($e->getCode() >= 100 ? $e->getCode() : 500, [], $e->getMessage());
54
        }
55
56
        return $response;
57
    }
58
59
    /**
60
     * Parses the JSON response to an array.
61
     *
62
     * @param ResponseInterface $response
63
     *
64
     * @return array
65
     */
66
    protected function parseJson(ResponseInterface $response)
67
    {
68
        $body = (string) $response->getBody();
69
70
        if (!empty($body)) {
71
            $body = json_decode($body, true);
72
        }
73
74
        return empty($body) ? [] : $body;
75
    }
76
}
77