GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#65)
by Ha
04:16
created

Builder::httpClient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 2
crap 2
1
<?php declare (strict_types = 1);
2
3
namespace OpenStack\Common\Service;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\ClientInterface;
7
use GuzzleHttp\Middleware as GuzzleMiddleware;
8
use OpenStack\Common\Auth\IdentityService;
9
use OpenStack\Common\Auth\Token;
10
use OpenStack\Common\Transport\HandlerStack;
11
use OpenStack\Common\Transport\Middleware;
12
use OpenStack\Common\Transport\Utils;
13
14
/**
15
 * A Builder for easily creating OpenStack services.
16
 *
17
 * @package OpenStack\Common\Service
18
 */
19
class Builder
20
{
21
    /**
22
     * Global options that will be applied to every service created by this builder.
23
     *
24
     * @var array
25
     */
26
    private $globalOptions = [];
27
28
    /** @var string */
29
    private $rootNamespace;
30
31
    /**
32
     * Defaults that will be applied to options if no values are provided by the user.
33
     *
34
     * @var array
35
     */
36
    private $defaults = ['urlType' => 'publicURL'];
37
38
    /**
39
     * @param array  $globalOptions  Options that will be applied to every service created by this builder.
40
     *                               Eventually they will be merged (and if necessary overridden) by the
41 9
     *                               service-specific options passed in.
42
     * @param string $rootNamespace  API classes' root namespace
43 9
     */
44 9
    public function __construct(array $globalOptions = [], $rootNamespace = 'OpenStack')
45
    {
46
        $this->globalOptions = $globalOptions;
47
        $this->rootNamespace = $rootNamespace;
48
    }
49
50
    private function getClasses($namespace)
51
    {
52
        $namespace = $this->rootNamespace . '\\' . $namespace;
53
        $classes   = [$namespace.'\\Api', $namespace.'\\Service'];
54 2
55
        foreach ($classes as $class) {
56 2
            if (!class_exists($class)) {
57
                throw new \RuntimeException(sprintf("%s does not exist", $class));
58
            }
59 2
        }
60 2
61 2
        return $classes;
62
    }
63
64
    /**
65
     * This method will return an OpenStack service ready fully built and ready for use. There is
66
     * some initial setup that may prohibit users from directly instantiating the service class
67
     * directly - this setup includes the configuration of the HTTP client's base URL, and the
68
     * attachment of an authentication handler.
69
     *
70
     * @param string $namespace      The namespace of the service
71
     * @param array  $serviceOptions The service-specific options to use
72
     *
73
     * @return \OpenStack\Common\Service\ServiceInterface
74
     *
75
     * @throws \Exception
76
     */
77
    public function createService(string $namespace, array $serviceOptions = []): ServiceInterface
78 9
    {
79
        $options = $this->mergeOptions($serviceOptions);
80 9
81
        $this->stockAuthHandler($options);
82 6
        $this->stockHttpClient($options, $namespace);
83 6
84 6
        list($apiClass, $serviceClass) = $this->getClasses($namespace);
85
86 2
        return new $serviceClass($options['httpClient'], new $apiClass());
87
    }
88 2
89
    private function stockHttpClient(array &$options, string $serviceName)
90
    {
91 6
        if (!isset($options['httpClient']) || !($options['httpClient'] instanceof ClientInterface)) {
92
            if (stripos($serviceName, 'identity') !== false) {
93 6
                $baseUrl = $options['authUrl'];
94 6
                $stack = $this->getStack($options['authHandler']);
95 1
            } else {
96 1
                list($token, $baseUrl) = $options['identityService']->authenticate($options);
97 1
                $stack = $this->getStack($options['authHandler'], $token);
98 5
            }
99 1
100
            $this->addDebugMiddleware($options, $stack);
101
102 2
            $options['httpClient'] = $this->httpClient($baseUrl, $stack);
103
        }
104 2
    }
105 2
106 2
    /**
107
     * @codeCoverageIgnore
108
     */
109
    private function addDebugMiddleware(array $options, HandlerStack &$stack)
110
    {
111
        if (!empty($options['debugLog'])
112
            && !empty($options['logger'])
113
            && !empty($options['messageFormatter'])
114
        ) {
115
            $stack->push(GuzzleMiddleware::log($options['logger'], $options['messageFormatter']));
116
        }
117
    }
118
119
    /**
120
     * @param array $options
121 6
     *
122
     * @codeCoverageIgnore
123 6
     */
124 5
    private function stockAuthHandler(array &$options)
125 5
    {
126 5
        if (!isset($options['authHandler'])) {
127 6
            $options['authHandler'] = function () use ($options) {
128
                return $options['identityService']->authenticate($options)[0];
129
            };
130
        }
131
    }
132
133
    private function getStack(callable $authHandler, Token $token = null): HandlerStack
134
    {
135
        $stack = HandlerStack::create();
136
        $stack->push(Middleware::authHandler($authHandler, $token));
137
        return $stack;
138
    }
139
140
    private function httpClient(string $baseUrl, HandlerStack $stack): ClientInterface
141
    {
142 2
        $clientOptions = [
143
            'base_uri' => Utils::normalizeUrl($baseUrl),
144 2
            'handler'  => $stack,
145 2
        ];
146 2
147
        if (isset($this->globalOptions['requestOptions'])) {
148
            $clientOptions = array_merge($this->globalOptions['requestOptions'], $clientOptions);
149 6
        }
150
151 6
        return new Client($clientOptions);
152 6
    }
153 6
154 6
    private function mergeOptions(array $serviceOptions): array
155
    {
156
        $options = array_merge($this->defaults, $this->globalOptions, $serviceOptions);
157 9
158
        if (!isset($options['authUrl'])) {
159 9
            throw new \InvalidArgumentException('"authUrl" is a required option');
160
        }
161 9
162 3
        if (!isset($options['identityService']) || !($options['identityService'] instanceof IdentityService)) {
163
            throw new \InvalidArgumentException(sprintf(
164
                '"identityService" must be specified and implement %s', IdentityService::class
165 6
            ));
166
        }
167
168
        return $options;
169
    }
170
}
171