Completed
Pull Request — master (#365)
by Alessandro
03:29
created

HttpDispatcher   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 316
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 98.95%

Importance

Changes 0
Metric Value
wmc 39
lcom 1
cbo 15
dl 0
loc 316
ccs 94
cts 95
cp 0.9895
rs 7.6254
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 3
B invalidate() 0 14 5
D flush() 0 39 9
A getServers() 0 4 1
C fanOut() 0 49 9
A setServers() 0 7 2
A setBaseUri() 0 10 2
C filterUri() 0 36 7
A getRequestSignature() 0 7 1
1
<?php
2
3
/*
4
 * This file is part of the FOSHttpCache package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\HttpCache\ProxyClient;
13
14
use FOS\HttpCache\Exception\ExceptionCollection;
15
use FOS\HttpCache\Exception\InvalidArgumentException;
16
use FOS\HttpCache\Exception\InvalidUrlException;
17
use FOS\HttpCache\Exception\MissingHostException;
18
use FOS\HttpCache\Exception\ProxyResponseException;
19
use FOS\HttpCache\Exception\ProxyUnreachableException;
20
use Http\Client\Common\Plugin\ErrorPlugin;
21
use Http\Client\Common\PluginClient;
22
use Http\Client\Exception\HttpException;
23
use Http\Client\Exception\RequestException;
24
use Http\Client\HttpAsyncClient;
25
use Http\Discovery\HttpAsyncClientDiscovery;
26
use Http\Discovery\UriFactoryDiscovery;
27
use Http\Message\UriFactory;
28
use Http\Promise\Promise;
29
use Psr\Http\Message\RequestInterface;
30
use Psr\Http\Message\UriInterface;
31
32
/**
33
 * Queue and send HTTP requests with a Httplug asynchronous client.
34
 *
35
 * @author David Buchmann <[email protected]>
36
 */
37
class HttpDispatcher
38
{
39
    /**
40
     * @var HttpAsyncClient
41
     */
42
    private $httpClient;
43
44
    /**
45
     * @var UriFactory
46
     */
47
    private $uriFactory;
48
49
    /**
50
     * Queued requests.
51
     *
52
     * @var RequestInterface[]
53
     */
54
    private $queue = [];
55
56
    /**
57
     * Caching proxy server host names or IP addresses.
58
     *
59
     * @var UriInterface[]
60
     */
61
    private $servers;
62
63
    /**
64
     * Application host name and optional base URL.
65
     *
66
     * @var UriInterface
67
     */
68
    private $baseUri;
69
70
    /**
71
     * If you specify a custom HTTP client, make sure that it converts HTTP
72
     * errors to exceptions.
73
     *
74
     * If your proxy server IPs can not be statically configured, extend this
75
     * class and overwrite getServers. Be sure to have some caching in
76
     * getServers.
77
     *
78
     * @param string[]             $servers    Caching proxy server hostnames or IP
79
     *                                         addresses, including port if not port 80.
80
     *                                         E.g. ['127.0.0.1:6081']
81
     * @param string               $baseUri    Default application hostname, optionally
82
     *                                         including base URL, for purge and refresh
83
     *                                         requests (optional). This is required if
84
     *                                         you purge and refresh paths instead of
85
     *                                         absolute URLs
86
     * @param HttpAsyncClient|null $httpClient Client capable of sending HTTP requests. If no
87
     *                                         client is supplied, a default one is created
88
     * @param UriFactory|null      $uriFactory Factory for PSR-7 URIs. If not specified, a
89
     *                                         default one is created
90
     */
91 38
    public function __construct(
92
        array $servers,
93
        $baseUri = '',
94
        HttpAsyncClient $httpClient = null,
95
        UriFactory $uriFactory = null
96
    ) {
97 38
        if (!$httpClient) {
98 26
            $httpClient = new PluginClient(
99 26
                HttpAsyncClientDiscovery::find(),
100 26
                [new ErrorPlugin()]
101
            );
102
        }
103 38
        $this->httpClient = $httpClient;
104 38
        $this->uriFactory = $uriFactory ?: UriFactoryDiscovery::find();
105
106 38
        $this->setServers($servers);
107 35
        $this->setBaseUri($baseUri);
108 34
    }
109
110
    /**
111
     * Queue invalidation request.
112
     *
113
     * @param RequestInterface $invalidationRequest
114
     * @param bool             $validateHost        If false, do not validate that we either have a
115
     *                                              base uri or the invalidation request specifies
116
     *                                              the host
117
     */
118 33
    public function invalidate(RequestInterface $invalidationRequest, $validateHost = true)
119
    {
120 33
        if ($validateHost && !$this->baseUri && !$invalidationRequest->getUri()->getHost()) {
121 1
            throw MissingHostException::missingHost((string) $invalidationRequest->getUri());
122
        }
123
124 32
        $signature = $this->getRequestSignature($invalidationRequest);
125
126 32
        if (isset($this->queue[$signature])) {
127 1
            return;
128
        }
129
130 32
        $this->queue[$signature] = $invalidationRequest;
131 32
    }
132
133
    /**
134
     * Send all pending invalidation requests and make sure the requests have terminated and gather exceptions.
135
     *
136
     * @return int The number of cache invalidations performed per caching server
137
     *
138
     * @throws ExceptionCollection If any errors occurred during flush
139
     */
140 33
    public function flush()
141
    {
142 33
        $queue = $this->queue;
143 33
        $this->queue = [];
144
        /** @var Promise[] $promises */
145 33
        $promises = [];
146
147 33
        $exceptions = new ExceptionCollection();
148
149 33
        foreach ($queue as $request) {
150 32
            foreach ($this->fanOut($request) as $proxyRequest) {
151
                try {
152 32
                    $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
153 1
                } catch (\Exception $e) {
154 32
                    $exceptions->add(new InvalidArgumentException($e));
155
                }
156
            }
157
        }
158
159 33
        foreach ($promises as $promise) {
160
            try {
161 32
                $promise->wait();
162 4
            } catch (HttpException $exception) {
163 2
                $exceptions->add(ProxyResponseException::proxyResponse($exception));
164 2
            } catch (RequestException $exception) {
165 2
                $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
166
            } catch (\Exception $exception) {
167
                // @codeCoverageIgnoreStart
168
                $exceptions->add(new InvalidArgumentException($exception));
169
                // @codeCoverageIgnoreEnd
170
            }
171
        }
172
173 33
        if (count($exceptions)) {
174 5
            throw $exceptions;
175
        }
176
177 31
        return count($queue);
178
    }
179
180
    /**
181
     * Get the list of servers to send invalidation requests to.
182
     *
183
     * @return UriInterface[]
184
     */
185 32
    protected function getServers()
186
    {
187 32
        return $this->servers;
188
    }
189
190
    /**
191
     * Duplicate a request for each caching server.
192
     *
193
     * @param RequestInterface $request The request to duplicate for each configured server
194
     *
195
     * @return RequestInterface[]
196
     */
197 32
    private function fanOut(RequestInterface $request)
198
    {
199 32
        $requests = [];
200
201 32
        $uri = $request->getUri();
202
203
        // If a base URI is configured, try to make partial invalidation
204
        // requests complete.
205 32
        if ($this->baseUri) {
206 30
            if ($uri->getHost()) {
207
                // Absolute URI: does it already have a scheme?
208 5
                if (!$uri->getScheme() && $this->baseUri->getScheme() !== '') {
209 5
                    $uri = $uri->withScheme($this->baseUri->getScheme());
210
                }
211
            } else {
212
                // Relative URI
213 25
                if ($this->baseUri->getHost() !== '') {
214 25
                    $uri = $uri->withHost($this->baseUri->getHost());
215
                }
216
217 25
                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...
218 16
                    $uri = $uri->withPort($this->baseUri->getPort());
219
                }
220
221
                // Base path
222 25
                if ($this->baseUri->getPath() !== '') {
223 1
                    $path = $this->baseUri->getPath().'/'.ltrim($uri->getPath(), '/');
224 1
                    $uri = $uri->withPath($path);
225
                }
226
            }
227
        }
228
229
        // Close connections to make sure invalidation (PURGE/BAN) requests
230
        // will not interfere with content (GET) requests.
231 32
        $request = $request->withUri($uri)->withHeader('Connection', 'Close');
232
233
        // Create a request to each caching proxy server
234 32
        foreach ($this->getServers() as $server) {
235 32
            $requests[] = $request->withUri(
236
                $uri
237 32
                    ->withScheme($server->getScheme())
238 32
                    ->withHost($server->getHost())
239 32
                    ->withPort($server->getPort()),
240 32
                true    // Preserve application Host header
241
            );
242
        }
243
244 32
        return $requests;
245
    }
246
247
    /**
248
     * Set caching proxy server URI objects, validating them.
249
     *
250
     * @param string[] $servers Caching proxy proxy server hostnames or IP
251
     *                          addresses, including port if not port 80.
252
     *                          E.g. ['127.0.0.1:6081']
253
     *
254
     * @throws InvalidUrlException If server is invalid or contains URL
255
     *                             parts other than scheme, host, port
256
     */
257 38
    private function setServers(array $servers)
258
    {
259 38
        $this->servers = [];
260 38
        foreach ($servers as $server) {
261 38
            $this->servers[] = $this->filterUri($server, ['scheme', 'host', 'port']);
262
        }
263 35
    }
264
265
    /**
266
     * Set application base URI that will be prefixed to relative purge and
267
     * refresh requests, and validate it.
268
     *
269
     * @param string $uriString Your application’s base URI
270
     *
271
     * @throws InvalidUrlException If the base URI is not a valid URI
272
     */
273 35
    private function setBaseUri($uriString = null)
274
    {
275 35
        if (!$uriString) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uriString of type string|null is loosely compared to false; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
276 3
            $this->baseUri = null;
277
278 3
            return;
279
        }
280
281 32
        $this->baseUri = $this->filterUri($uriString);
282 31
    }
283
284
    /**
285
     * Filter a URL.
286
     *
287
     * Prefix the URL with "http://" if it has no scheme, then check the URL
288
     * for validity. You can specify what parts of the URL are allowed.
289
     *
290
     * @param string   $uriString
291
     * @param string[] $allowedParts Array of allowed URL parts (optional)
292
     *
293
     * @return UriInterface Filtered URI (with default scheme if there was no scheme)
294
     *
295
     * @throws InvalidUrlException If URL is invalid, the scheme is not http or
296
     *                             contains parts that are not expected
297
     */
298 38
    private function filterUri($uriString, array $allowedParts = [])
299
    {
300 38
        if (!is_string($uriString)) {
301 1
            throw new \InvalidArgumentException(sprintf(
302 1
                'URI parameter must be a string, %s given',
303 1
                gettype($uriString)
304
            ));
305
        }
306
307
        // Creating a PSR-7 URI without scheme (with parse_url) results in the
308
        // original hostname to be seen as path. So first add a scheme if none
309
        // is given.
310 38
        if (false === strpos($uriString, '://')) {
311 34
            $uriString = sprintf('%s://%s', 'http', $uriString);
312
        }
313
314
        try {
315 38
            $uri = $this->uriFactory->createUri($uriString);
316 1
        } catch (\InvalidArgumentException $e) {
317 1
            throw InvalidUrlException::invalidUrl($uriString);
318
        }
319
320 37
        if (!$uri->getScheme()) {
321 1
            throw InvalidUrlException::invalidUrl($uriString, 'empty scheme');
322
        }
323
324 36
        if (count($allowedParts) > 0) {
325 36
            $parts = parse_url((string) $uri);
326 36
            $diff = array_diff(array_keys($parts), $allowedParts);
327 36
            if (count($diff) > 0) {
328 1
                throw InvalidUrlException::invalidUrlParts($uriString, $allowedParts);
329
            }
330
        }
331
332 35
        return $uri;
333
    }
334
335
    /**
336
     * Build a request signature based on the request data. Unique for every different request, identical
337
     * for the same requests.
338
     *
339
     * This signature is used to avoid sending the same invalidation request twice.
340
     *
341
     * @param RequestInterface $request An invalidation request
342
     *
343
     * @return string A signature for this request
344
     */
345 32
    private function getRequestSignature(RequestInterface $request)
346
    {
347 32
        $headers = $request->getHeaders();
348 32
        ksort($headers);
349
350 32
        return sha1($request->getMethod()."\n".$request->getUri()."\n".var_export($headers, true));
351
    }
352
}
353