Completed
Pull Request — master (#272)
by David
85:16 queued 73:52
created

HttpAdapter::setServers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 0
cp 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 6
1
<?php
2
3
namespace FOS\HttpCache\ProxyClient\Http;
4
5
use FOS\HttpCache\Exception\ExceptionCollection;
6
use FOS\HttpCache\Exception\InvalidArgumentException;
7
use FOS\HttpCache\Exception\InvalidUrlException;
8
use FOS\HttpCache\Exception\ProxyResponseException;
9
use FOS\HttpCache\Exception\ProxyUnreachableException;
10
use Http\Client\Exception;
11
use Http\Client\Exception\HttpException;
12
use Http\Client\Exception\RequestException;
13
use Http\Client\HttpAsyncClient;
14
use Http\Message\UriFactory;
15
use Http\Promise\Promise;
16
use Psr\Http\Message\RequestInterface;
17
use Psr\Http\Message\UriInterface;
18
19
/**
20
 * An adapter to work with the Httplug asynchronous client.
21
 *
22
 * @author David Buchmann <[email protected]>
23
 */
24
class HttpAdapter
25
{
26
    /**
27
     * @var HttpAsyncClient
28
     */
29
    private $httpClient;
30
31
    /**
32
     * @var UriFactory
33
     */
34
    private $uriFactory;
35
36
    /**
37
     * Queued requests
38
     *
39
     * @var RequestInterface[]
40
     */
41
    private $queue = [];
42
43
    /**
44
     * Caching proxy server host names or IP addresses.
45
     *
46
     * @var UriInterface[]
47
     */
48
    private $servers;
49
50
    /**
51
     * Application host name and optional base URL.
52
     *
53
     * @var UriInterface
54
     */
55
    private $baseUri;
56
57
    /**
58
     * @param string[] $servers Caching proxy server hostnames or IP
59
     *                          addresses, including port if not port 80.
60
     *                          E.g. ['127.0.0.1:6081']
61
     * @param string   $baseUri Default application hostname, optionally
62
     *                          including base URL, for purge and refresh
63 45
     *                          requests (optional). This is required if
64
     *                          you purge and refresh paths instead of
65 45
     *                          absolute URLs.
66 42
     * @param HttpAsyncClient $httpClient
67 42
     * @param UriFactory      $uriFactory
68 42
     */
69
    public function __construct(array $servers, $baseUri, HttpAsyncClient $httpClient, UriFactory $uriFactory)
70
    {
71
        $this->setServers($servers);
72
        $this->setBaseUri($baseUri);
73
        $this->httpClient = $httpClient;
74
        $this->uriFactory = $uriFactory;
75 37
    }
76
77 37
    /**
78
     * Queue invalidation request.
79 37
     *
80 1
     * @param RequestInterface $invalidationRequest
81
     */
82
    public function invalidate(RequestInterface $invalidationRequest)
83 37
    {
84 37
        $signature = $this->getRequestSignature($invalidationRequest);
85
86
        if (isset($this->queue[$signature])) {
87
            return;
88
        }
89
90
        $this->queue[$signature] = $invalidationRequest;
91
    }
92
93 38
    /**
94
     * Send all pending invalidation requests and make sure the requests have terminated and gather exceptions.
95 38
     *
96 38
     * @return int The number of cache invalidations performed per caching server.
97
     *
98 38
     * @throws ExceptionCollection If any errors occurred during flush.
99
     */
100 38
    public function flush()
101
    {
102 38
        $queue = $this->queue;
103 37
        $this->queue = [];
104 37
        /** @var Promise[] $promises */
105 37
        $promises = [];
106 38
107
        $exceptions = new ExceptionCollection();
108 38
109
        foreach ($queue as $request) {
110
            foreach ($this->fanOut($request) as $proxyRequest) {
111
                $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
112 38
            }
113
        }
114 37
115 37
        if (count($exceptions)) {
116
            throw new ExceptionCollection($exceptions);
0 ignored issues
show
Documentation introduced by
$exceptions is of type object<FOS\HttpCache\Exc...on\ExceptionCollection>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
117 1
        }
118 1
119 1
        foreach ($promises as $promise) {
120
            try {
121
                $promise->wait();
122 38
            } catch (HttpException $exception) {
123
                $exceptions->add(ProxyResponseException::proxyResponse($exception->getResponse()));
124 38
            } catch (RequestException $exception) {
125 1
                $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
126
            } catch (\Exception $exception)  {
127
                    $exceptions->add(new InvalidArgumentException($exception));
128 38
            }
129
        }
130
131
        if (count($exceptions)) {
132
            throw $exceptions;
133
        }
134
135
        return count($queue);
136
    }
137
138 37
    /**
139
     * Duplicate a request for each caching server
140 37
     *
141
     * @param RequestInterface $request The request to duplicate for each configured server
142 37
     *
143
     * @return RequestInterface[]
144
     */
145
    private function fanOut(RequestInterface $request)
146 37
    {
147 34
        $requests = [];
148
149 2
        $uri = $request->getUri();
150
151
        // If a base URI is configured, try to make partial invalidation
152 2
        // requests complete.
153
        if ($this->baseUri) {
154 32
            if ($uri->getHost()) {
155 32
                // Absolute URI: does it already have a scheme?
156 32
                if (!$uri->getScheme() && $this->baseUri->getScheme() !== '') {
157
                    $uri = $uri->withScheme($this->baseUri->getScheme());
158 32
                }
159 13
            } else {
160 13
                // Relative URI
161
                if ($this->baseUri->getHost() !== '') {
162
                    $uri = $uri->withHost($this->baseUri->getHost());
163 32
                }
164 1
165 1
                if ($this->baseUri->getPort()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->baseUri->getPort() of type null|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
166 1
                    $uri = $uri->withPort($this->baseUri->getPort());
167
                }
168 34
169
                // Base path
170
                if ($this->baseUri->getPath() !== '') {
171
                    $path = $this->baseUri->getPath() . '/' . ltrim($uri->getPath(), '/');
172 37
                    $uri = $uri->withPath($path);
173
                }
174
            }
175 37
        }
176 37
177
        // Close connections to make sure invalidation (PURGE/BAN) requests
178 37
        // will not interfere with content (GET) requests.
179 37
        $request = $request->withUri($uri)->withHeader('Connection', 'Close');
180 37
181 37
        // Create a request to each caching proxy server
182
        foreach ($this->servers as $server) {
183 37
            $requests[] = $request->withUri(
184 37
                $uri
185
                    ->withScheme($server->getScheme())
186 37
                    ->withHost($server->getHost())
187
                    ->withPort($server->getPort())
188
                ,
189
                true    // Preserve application Host header
190
            );
191
        }
192
193
        return $requests;
194
    }
195
196
    /**
197
     * Set caching proxy server URI objects, validating them.
198
     *
199 45
     * @param string[] $servers Caching proxy proxy server hostnames or IP
200
     *                          addresses, including port if not port 80.
201 45
     *                          E.g. ['127.0.0.1:6081']
202 45
     *
203 45
     * @throws InvalidUrlException If server is invalid or contains URL
204 42
     *                             parts other than scheme, host, port
205 42
     */
206
    private function setServers(array $servers)
207
    {
208
        $this->servers = [];
209
        foreach ($servers as $server) {
210
            $this->servers[] = $this->filterUri($server, ['scheme', 'host', 'port']);
211
        }
212
    }
213
214
    /**
215 42
     * Set application base URI that will be prefixed to relative purge and
216
     * refresh requests, and validate it.
217 42
     *
218 6
     * @param string $uriString Your application’s base URI
219
     *
220 6
     * @throws InvalidUrlException If the base URI is not a valid URI.
221
     */
222
    private function setBaseUri($uriString = null)
223 36
    {
224 36
        if (null === $uriString) {
225
            $this->baseUri = null;
226
227
            return;
228
        }
229
230
        $this->baseUri = $this->filterUri($uriString);
231
    }
232
233
    /**
234
     * Filter a URL
235
     *
236
     * Prefix the URL with "http://" if it has no scheme, then check the URL
237
     * for validity. You can specify what parts of the URL are allowed.
238
     *
239
     * @param string       $uriString
240 45
     * @param string[]     $allowedParts Array of allowed URL parts (optional)
241
     *
242
     * @return UriInterface Filtered URI (with default scheme if there was no scheme)
243
     *
244
     * @throws InvalidUrlException If URL is invalid, the scheme is not http or
245 45
     *                             contains parts that are not expected.
246 40
     */
247 40
    private function filterUri($uriString, array $allowedParts = [])
248
    {
249
        // Creating a PSR-7 URI without scheme (with parse_url) results in the
250 45
        // original hostname to be seen as path. So first add a scheme if none
251 45
        // is given.
252 1
        if (false === strpos($uriString, '://')) {
253
            $uriString = sprintf('%s://%s', 'http', $uriString);
254
        }
255 44
256 1
        try {
257
            $uri = $this->uriFactory->createUri($uriString);
258
        } catch (\InvalidArgumentException $e) {
259 43
            throw InvalidUrlException::invalidUrl($uriString);
260 43
        }
261 43
262 43
        if (!$uri->getScheme()) {
263 1
            throw InvalidUrlException::invalidUrl($uriString, 'empty scheme');
264
        }
265 42
266
        if (count($allowedParts) > 0) {
267 42
            $parts = parse_url((string) $uri);
268
            $diff = array_diff(array_keys($parts), $allowedParts);
269
            if (count($diff) > 0) {
270
                throw InvalidUrlException::invalidUrlParts($uriString, $allowedParts);
271
            }
272
        }
273
274
        return $uri;
275
    }
276
277
    /**
278
     * Build a request signature based on the request data. Unique for every different request, identical
279
     * for the same requests.
280 37
     *
281
     * This signature is used to avoid sending the same invalidation request twice.
282 37
     *
283 37
     * @param RequestInterface $request An invalidation request.
284
     *
285 37
     * @return string A signature for this request.
286
     */
287
    private function getRequestSignature(RequestInterface $request)
288
    {
289
        $headers = $request->getHeaders();
290
        ksort($headers);
291
292
        return md5($request->getMethod(). "\n" . $request->getUri(). "\n" . var_export($headers, true));
293
    }
294
}
295