Test Failed
Branch master (d80a5c)
by
unknown
05:06
created

Client::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author  Rizart Dokollari <[email protected]>
4
 * @since   12/24/17
5
 */
6
7
namespace ElasticEmail;
8
9
use GuzzleHttp\HandlerStack;
10
use GuzzleHttp\Middleware;
11
use GuzzleHttp\Psr7\Uri;
12
use Psr\Http\Message\RequestInterface;
13
use Psr\Http\Message\ResponseInterface;
14
15
16
/** HTTP client: sets correct base URI & api key. */
17
class Client extends \GuzzleHttp\Client
18
{
19
    static $baseUri = 'https://api.elasticemail.com/v2/';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $baseUri.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
20
21
    public function __construct($apiKey, array $middlewares = [])
22
    {
23
        if (empty($apiKey)) {
24
            throw new ElasticEmailException('ElasticEmail API key is missing.');
25
        }
26
27
        parent::__construct([
28
            'base_uri' => self::$baseUri,
29
            'handler'  => $this->handler($apiKey, $middlewares),
30
        ]);
31
    }
32
33
    public function handler($apikey, array $externalMiddlewares = [])
34
    {
35
        $stack = HandlerStack::create();
36
37
        $stack->push(
38
            Middleware::mapRequest(
39
                function (RequestInterface $request) use ($apikey) {
40
                    return $request->withUri(
41
                        Uri::withQueryValue(
42
                            $request->getUri(), 'apikey', $apikey
43
                        )
44
                    );
45
                }
46
            )
47
        );
48
49
        $stack->push(Middleware::mapResponse(
50
            function (ResponseInterface $response) {
51
52
                $body = json_decode((string)$response->getBody(), true);
53
54
                if ( ! $body['success']) {
55
                    throw new ElasticEmailException($body['error']);
56
                }
57
58
                return $response;
59
            }
60
        ));
61
62
        foreach ($externalMiddlewares as $middleware) {
63
            $stack->push($middleware);
64
        }
65
66
        return $stack;
67
    }
68
}