Connector::createRequest()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 18
c 3
b 0
f 0
nc 3
nop 2
dl 0
loc 27
rs 9.3554
1
<?php
2
3
namespace AcquiaCloudApi\Connector;
4
5
use League\OAuth2\Client\Provider\AbstractProvider;
6
use League\OAuth2\Client\Provider\GenericProvider;
7
use League\OAuth2\Client\Token\AccessTokenInterface;
8
use GuzzleHttp\Client as GuzzleClient;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
12
use Symfony\Component\Filesystem\Path;
13
14
/**
15
 * Class Connector
16
 *
17
 * @package AcquiaCloudApi\CloudApi
18
 */
19
class Connector implements ConnectorInterface
20
{
21
    /**
22
     * @var string The base URI for Acquia Cloud API.
23
     */
24
    private string $baseUri;
25
26
    /**
27
     * @var string The URL access token for Accounts API.
28
     */
29
    private string $urlAccessToken;
30
31
    /**
32
     * @var string|null The Client ID.
33
     */
34
    private ?string $clientId;
35
36
    /**
37
     * @var GenericProvider The OAuth 2.0 provider to use in communication.
38
     */
39
    protected AbstractProvider $provider;
40
41
    /**
42
     * @var GuzzleClient The client used to make HTTP requests to the API.
43
     */
44
    protected GuzzleClient $client;
45
46
    /**
47
     * @var AccessTokenInterface|null The generated OAuth 2.0 access token.
48
     */
49
    protected ?AccessTokenInterface $accessToken;
50
51
    /**
52
     * @param array<string, string> $config
53
     */
54
    public function __construct(array $config, ?string $base_uri = null, ?string $url_access_token = null)
55
    {
56
        $this->baseUri = ConnectorInterface::BASE_URI;
57
        if ($base_uri) {
58
            $this->baseUri = $base_uri;
59
        }
60
61
        $this->urlAccessToken = ConnectorInterface::URL_ACCESS_TOKEN;
62
        if ($url_access_token) {
63
            $this->urlAccessToken = $url_access_token;
64
        }
65
66
        $this->clientId = $config['key'];
67
68
        $this->provider = new GenericProvider(
69
            [
70
            'clientId'                => $config['key'],
71
            'clientSecret'            => $config['secret'],
72
            'urlAuthorize'            => '',
73
            'urlAccessToken'          => $this->getUrlAccessToken(),
74
            'urlResourceOwnerDetails' => '',
75
            ]
76
        );
77
78
        $this->client = new GuzzleClient();
79
    }
80
81
    public function getBaseUri(): string
82
    {
83
        return $this->baseUri;
84
    }
85
86
    public function getUrlAccessToken(): string
87
    {
88
        return $this->urlAccessToken;
89
    }
90
91
    /**
92
     * @inheritdoc
93
     * @throws \Psr\Cache\InvalidArgumentException
94
     */
95
    public function createRequest(string $verb, string $path): RequestInterface
96
    {
97
        if (!isset($this->accessToken) || $this->accessToken->hasExpired()) {
0 ignored issues
show
Bug introduced by
The method hasExpired() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

97
        if (!isset($this->accessToken) || $this->accessToken->/** @scrutinizer ignore-call */ hasExpired()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
98
            $xdgCacheHome = getenv('XDG_CACHE_HOME');
99
            if (!$xdgCacheHome) {
100
                $xdgCacheHome = Path::join(Path::getHomeDirectory(), '.cache');
101
            }
102
            $directory = Path::join($xdgCacheHome, 'acquia-php-sdk-v2');
103
            /** @infection-ignore-all */
104
            $cache = new FilesystemAdapter('cache', 300, $directory);
105
            $orgUuid = getenv('AH_ORGANIZATION_UUID');
106
            $cacheKey = 'cloudapi-token-' . $this->clientId . $orgUuid;
107
            $accessToken = $cache->get($cacheKey, function () use ($orgUuid) {
108
                $options = [];
109
                if ($orgUuid) {
110
                    $options['scope'] = 'organization:' . $orgUuid;
111
                }
112
                return $this->provider->getAccessToken('client_credentials', $options);
113
            });
114
115
            $this->accessToken = $accessToken;
116
        }
117
118
        return $this->provider->getAuthenticatedRequest(
119
            $verb,
120
            $this->getBaseUri() . $path,
121
            $this->accessToken
122
        );
123
    }
124
125
    /**
126
     * @inheritdoc
127
     * @throws \GuzzleHttp\Exception\GuzzleException
128
     * @throws \Psr\Cache\InvalidArgumentException
129
     */
130
    public function sendRequest(string $verb, string $path, array $options): ResponseInterface
131
    {
132
        $request = $this->createRequest($verb, $path);
133
        return $this->client->send($request, $options);
134
    }
135
}
136