Client   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 29
c 0
b 0
f 0
dl 0
loc 60
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handler() 0 41 4
A __construct() 0 12 2
1
<?php
2
3
namespace ElasticEmail;
4
5
use Exception;
6
use GuzzleHttp\HandlerStack;
7
use GuzzleHttp\Middleware;
8
use GuzzleHttp\Psr7\Uri;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
12
/** HTTP client: sets correct base URI & api key and other middlewares. */
13
class Client extends \GuzzleHttp\Client
14
{
15
    public static $baseUri = 'https://api.elasticemail.com/v2/';
16
17
    public function __construct(
18
        string $apiKey,
19
        array $middlewares = [],
20
        $handler = null
21
    ) {
22
        if (empty($apiKey)) {
23
            throw new ElasticEmailException('ElasticEmail API key is missing.');
24
        }
25
26
        parent::__construct([
27
            'base_uri' => self::$baseUri,
28
            'handler' => $this->handler($apiKey, $middlewares, $handler),
29
        ]);
30
    }
31
32
    public function handler($apikey, array $middlewares = [], $handler = null)
33
    {
34
        $stack = HandlerStack::create($handler);
35
36
        $stack->push(
37
            Middleware::mapRequest(
38
                function (RequestInterface $request) use ($apikey) {
39
                    return $request->withUri(
40
                        Uri::withQueryValue(
41
                            $request->getUri(),
42
                            'apikey',
43
                            $apikey
44
                        )
45
                    );
46
                }
47
            )
48
        );
49
50
        $stack->push(Middleware::mapResponse(
51
            function (ResponseInterface $response) {
52
53
                try {
54
                    $body = json_decode((string)$response->getBody(), true);
55
                } catch (Exception $error) {
56
                    $genericError = 'Unable to decode JSON response.';
57
                    throw new ElasticEmailException($genericError);
58
                }
59
60
                if (! $body['success']) {
61
                    throw new ElasticEmailException($body['error']);
62
                }
63
64
                return $response;
65
            }
66
        ));
67
68
        foreach ($middlewares as $middleware) {
69
            $stack->push($middleware);
70
        }
71
72
        return $stack;
73
    }
74
}
75