Completed
Branch cleanup (1408c8)
by Paul
04:39
created

HTTPClientFactory::setAPIHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 3
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace LibLynx\Connect\HTTPClient;
4
5
use GuzzleHttp\ClientInterface;
6
use GuzzleHttp\HandlerStack;
7
use GuzzleHttp\Client as GuzzleClient;
8
use kamermans\OAuth2\GrantType\ClientCredentials;
9
use kamermans\OAuth2\OAuth2Middleware;
10
use Kevinrob\GuzzleCache\CacheMiddleware;
11
use Kevinrob\GuzzleCache\Storage\Psr16CacheStorage;
12
use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy;
13
use Psr\SimpleCache\CacheInterface;
14
15
/**
16
 * Provides the means for creating an OAuth2-capable, cache-aware HTTP client
17
 *
18
 * This can also be modified to provide the means to test the client
19
 *
20
 * @package LibLynx\Connect
21
 */
22
class HTTPClientFactory
23
{
24
    /** @var CacheInterface */
25
    protected $cache;
26
27
    /** @var callable RequestStack handler for API requests */
28
    private $apiHandler = null;
29
30
    /** @var callable RequestStack handler for OAuth2 requests */
31
    private $oauth2Handler = null;
32
33 16
    public function __construct(callable $apiHandler = null, callable $oauth2Handler = null)
34
    {
35 16
        $this->apiHandler = $apiHandler;
36 16
        $this->oauth2Handler = $oauth2Handler;
37 16
    }
38
39 10
    public function create($apiRoot, $clientId, $clientSecret, CacheInterface $cache) : ClientInterface
40
    {
41
        //create our handler stack (which may be mocked in tests) and add the oauth and cache middleware
42 10
        $handlerStack = HandlerStack::create($this->apiHandler);
43 10
        $handlerStack->push($this->createOAuth2Middleware($apiRoot, $clientId, $clientSecret, $cache));
44 10
        $handlerStack->push($this->createCacheMiddleware($cache), 'cache');
45
46
        //now we can make our client
47 10
        $client = new GuzzleClient([
48 10
            'handler' => $handlerStack,
49 10
            'auth' => 'oauth',
50 10
            'base_uri' => $apiRoot
51
        ]);
52
53 10
        return $client;
54
    }
55
56
    /**
57
     * This is primarily to facilitate testing - we can add a MockHandler to return
58
     * test responses
59
     *
60
     * @param callable $handler
61
     * @return self
62
     */
63
    public function setAPIHandler(callable $handler)
64
    {
65
        $this->apiHandler = $handler;
66
        return $this;
67
    }
68
69
    /**
70
     * This is primarily to facilitate testing - we can add a MockHandler to return
71
     * test responses
72
     *
73
     * @param callable $handler
74
     * @return self
75
     */
76
    public function setOAuth2Handler(callable $handler)
77
    {
78
        $this->oauth2Handler = $handler;
79
        return $this;
80
    }
81
82 10
    protected function createOAuth2Middleware($apiRoot, $id, $secret, CacheInterface $cache): OAuth2Middleware
83
    {
84 10
        $handlerStack = HandlerStack::create($this->oauth2Handler);
85
86
        // Authorization client - this is used to request OAuth access tokens
87 10
        $reauth_client = new GuzzleClient([
88 10
            'handler' => $handlerStack,
89
            // URL for access_token request
90 10
            'base_uri' => $apiRoot . '/oauth/v2/token',
91
        ]);
92
        $reauth_config = [
93 10
            "client_id" => $id,
94 10
            "client_secret" => $secret
95
        ];
96 10
        $grant_type = new ClientCredentials($reauth_client, $reauth_config);
97 10
        $oauth = new OAuth2Middleware($grant_type);
98
99
        //use our cache to store tokens
100 10
        $oauth->setTokenPersistence(new SimpleCacheTokenPersistence($cache));
101
102 10
        return $oauth;
103
    }
104
105 10
    protected function createCacheMiddleware(CacheInterface $cache): CacheMiddleware
106
    {
107 10
        return new CacheMiddleware(
108 10
            new PrivateCacheStrategy(
109 10
                new Psr16CacheStorage($cache)
110
            )
111
        );
112
    }
113
}
114