Passed
Push — master ( 3e8a98...89fe35 )
by Robin
06:59 queued 24s
created

GuzzleClientFactory::baseUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Konsulting\JustGivingApiSdk\Support;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\HandlerStack;
7
use GuzzleHttp\Middleware;
8
use Illuminate\Support\Arr;
9
use Konsulting\JustGivingApiSdk\Support\Auth\AuthValue;
10
use Psr\Http\Message\ResponseInterface;
11
12
/**
13
 * Class GuzzleClientFactory
14
 *
15
 * Helper class to instantiate a Guzzle HTTP client with the correct configuration for passing into the JustGiving
16
 * client.
17
 */
18
class GuzzleClientFactory
19
{
20
    /** @var string */
21
    protected $apiVersion;
22
23
    /** @var string */
24
    protected $rootDomain;
25
26
    /** @var array */
27
    protected $userOptions;
28
29
    /** @var AuthValue */
30
    protected $auth;
31
32
    /**
33
     * GuzzleClientFactory constructor.
34
     *
35
     * @param AuthValue $auth
36
     * @param array     $options
37
     */
38 89
    public function __construct(AuthValue $auth, $options = [])
39
    {
40 89
        $this->rootDomain = Arr::pull($options, 'root_domain', 'https://api.justgiving.com');
41 89
        $this->apiVersion = Arr::pull($options, 'api_version', 1);
42 89
        $this->userOptions = $options;
43 89
        $this->auth = $auth;
44 89
    }
45
46
    /**
47
     * Set up the handler stack with middleware, configure options and instantiate the Guzzle client.
48
     *
49
     * @return Client
50
     */
51 89
    public function createClient()
52
    {
53 89
        $stack = HandlerStack::create();
54 89
        $stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
55 70
            return new Response($response);
56 89
        }));
57
58 89
        $defaultHeaders = ['Accept' => 'application/json'];
59
60 89
        return new Client(array_merge([
61 89
            'http_errors' => false,
62 89
            'handler'     => $stack,
63 89
            'base_uri'    => $this->baseUrl(),
64 89
            'headers'     => array_merge($defaultHeaders, $this->auth->getHeaders()),
65 89
        ], $this->userOptions));
66
    }
67
68
    /**
69
     * Return the base URL string for the API call.
70
     *
71
     * @return string
72
     */
73 89
    protected function baseUrl()
74
    {
75 89
        return $this->rootDomain . '/v' . $this->apiVersion . '/';
76
    }
77
}
78