ClientManager   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Test Coverage

Coverage 89.66%

Importance

Changes 0
Metric Value
eloc 30
dl 0
loc 77
ccs 26
cts 29
cp 0.8966
rs 10
c 0
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setHandler() 0 3 1
A createClientHandler() 0 8 2
A getClient() 0 25 2
A setClient() 0 5 1
A __construct() 0 4 1
1
<?php
2
3
namespace Glorand\Drip;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\HandlerStack;
7
8
abstract class ClientManager
9
{
10
    /** @var string */
11
    private $apiToken;
12
    /** @var string */
13
    private $userAgent;
14
    /** @var string */
15
    private $apiEndPoint = 'https://api.getdrip.com/v2/';
16
    /** @var Client|null */
17
    private $client = null;
18
    /** @var callable|null */
19
    private $handler = null;
20
21 9
    public function __construct(string $apiToken, string $userAgent)
22
    {
23 9
        $this->apiToken = $apiToken;
24 9
        $this->userAgent = $userAgent;
25 9
    }
26
27
    /**
28
     * @param array $options
29
     *
30
     * @return Client
31
     */
32 9
    public function getClient(array $options = [])
33
    {
34 9
        if (!is_null($this->client)) {
35 7
            return $this->client;
36
        }
37
38 9
        $options = array_merge(
39 9
            ['handler' => $this->createClientHandler()],
40 9
            $options,
41
            [
42 9
                'base_uri' => $this->apiEndPoint,
43
                'auth'     => [
44 9
                    $this->apiToken,
45 9
                    '',
46
                ],
47
                'headers'  => [
48 9
                    'Accept'       => 'application/vnd.api+json',
49 9
                    'Content-Type' => 'application/vnd.api+json',
50 9
                    'User-Agent'   => $this->userAgent,
51
                ],
52
            ]
53
        );
54 9
        $this->client = new Client($options);
55
56 9
        return $this->client;
57
    }
58
59
    public function setClient(Client $client): self
60
    {
61
        $this->client = $client;
62
63
        return $this;
64
    }
65
66
    /**
67
     * @param callable $handler
68
     */
69 9
    public function setHandler(callable $handler)
70
    {
71 9
        $this->handler = $handler;
72 9
    }
73
74
    /**
75
     * @return HandlerStack
76
     */
77 9
    private function createClientHandler(): HandlerStack
78
    {
79 9
        $stack = HandlerStack::create();
80 9
        if ($this->handler) {
81 9
            $stack->setHandler($this->handler);
82
        }
83
84 9
        return $stack;
85
    }
86
}
87