ClientManager::createClientHandler()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
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