Completed
Pull Request — master (#312)
by David
11:09
created

HttpDispatcher::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 4
nop 4
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\Http;
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\Exception\HttpException;
21
use Http\Client\Exception\RequestException;
22
use Http\Client\HttpAsyncClient;
23
use Http\Discovery\HttpAsyncClientDiscovery;
24
use Http\Discovery\UriFactoryDiscovery;
25
use Http\Message\UriFactory;
26
use Http\Promise\Promise;
27
use Psr\Http\Message\RequestInterface;
28
use Psr\Http\Message\UriInterface;
29
30
/**
31
 * Queue and send HTTP requests with a Httplug asynchronous client.
32
 *
33
 * @author David Buchmann <[email protected]>
34
 */
35
class HttpDispatcher
36
{
37
    /**
38
     * @var HttpAsyncClient
39
     */
40
    private $httpClient;
41
42
    /**
43
     * @var UriFactory
44
     */
45
    private $uriFactory;
46
47
    /**
48
     * Queued requests.
49
     *
50
     * @var RequestInterface[]
51
     */
52
    private $queue = [];
53
54
    /**
55
     * Caching proxy server host names or IP addresses.
56
     *
57
     * @var UriInterface[]
58
     */
59
    private $servers;
60
61
    /**
62
     * Application host name and optional base URL.
63
     *
64
     * @var UriInterface
65
     */
66
    private $baseUri;
67
68
    /**
69
     * @param string[]             $servers    Caching proxy server hostnames or IP
70
     *                                         addresses, including port if not port 80.
71
     *                                         E.g. ['127.0.0.1:6081']
72
     * @param string               $baseUri    Default application hostname, optionally
73
     *                                         including base URL, for purge and refresh
74
     *                                         requests (optional). This is required if
75
     *                                         you purge and refresh paths instead of
76
     *                                         absolute URLs
77
     * @param HttpAsyncClient|null $httpClient Client capable of sending HTTP requests. If no
78
     *                                         client is supplied, a default one is created
79
     * @param UriFactory|null      $uriFactory Factory for PSR-7 URIs. If not specified, a
80
     *                                         default one is created
81
     */
82
    public function __construct(
83
        array $servers,
84
        $baseUri = '',
85
        HttpAsyncClient $httpClient = null,
86
        UriFactory $uriFactory = null
87
    ) {
88
        $this->httpClient = $httpClient ?: HttpAsyncClientDiscovery::find();
89
        $this->uriFactory = $uriFactory ?: UriFactoryDiscovery::find();
90
91
        $this->setServers($servers);
92
        $this->setBaseUri($baseUri);
93
    }
94
95
    /**
96
     * Queue invalidation request.
97
     *
98
     * @param RequestInterface $invalidationRequest
99
     */
100
    public function invalidate(RequestInterface $invalidationRequest)
101
    {
102
        if (!$this->baseUri && !$invalidationRequest->getUri()->getHost()) {
103
            throw MissingHostException::missingHost((string) $invalidationRequest->getUri());
104
        }
105
106
        $signature = $this->getRequestSignature($invalidationRequest);
107
108
        if (isset($this->queue[$signature])) {
109
            return;
110
        }
111
112
        $this->queue[$signature] = $invalidationRequest;
113
    }
114
115
    /**
116
     * Send all pending invalidation requests and make sure the requests have terminated and gather exceptions.
117
     *
118
     * @return int The number of cache invalidations performed per caching server
119
     *
120
     * @throws ExceptionCollection If any errors occurred during flush
121
     */
122
    public function flush()
123
    {
124
        $queue = $this->queue;
125
        $this->queue = [];
126
        /** @var Promise[] $promises */
127
        $promises = [];
128
129
        $exceptions = new ExceptionCollection();
130
131
        foreach ($queue as $request) {
132
            foreach ($this->fanOut($request) as $proxyRequest) {
133
                try {
134
                    $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
135
                } catch (\Exception $e) {
136
                    $exceptions->add(new InvalidArgumentException($e));
137
                }
138
            }
139
        }
140
141
        foreach ($promises as $promise) {
142
            try {
143
                $promise->wait();
144
            } catch (HttpException $exception) {
145
                $exceptions->add(ProxyResponseException::proxyResponse($exception->getResponse()));
146
            } catch (RequestException $exception) {
147
                $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
148
            } catch (\Exception $exception) {
149
                // @codeCoverageIgnoreStart
150
                $exceptions->add(new InvalidArgumentException($exception));
151
                // @codeCoverageIgnoreEnd
152
            }
153
        }
154
155
        if (count($exceptions)) {
156
            throw $exceptions;
157
        }
158
159
        return count($queue);
160
    }
161
162
    /**
163
     * Duplicate a request for each caching server.
164
     *
165
     * @param RequestInterface $request The request to duplicate for each configured server
166
     *
167
     * @return RequestInterface[]
168
     */
169
    private function fanOut(RequestInterface $request)
170
    {
171
        $requests = [];
172
173
        $uri = $request->getUri();
174
175
        // If a base URI is configured, try to make partial invalidation
176
        // requests complete.
177
        if ($this->baseUri) {
178
            if ($uri->getHost()) {
179
                // Absolute URI: does it already have a scheme?
180
                if (!$uri->getScheme() && $this->baseUri->getScheme() !== '') {
181
                    $uri = $uri->withScheme($this->baseUri->getScheme());
182
                }
183
            } else {
184
                // Relative URI
185
                if ($this->baseUri->getHost() !== '') {
186
                    $uri = $uri->withHost($this->baseUri->getHost());
187
                }
188
189
                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...
190
                    $uri = $uri->withPort($this->baseUri->getPort());
191
                }
192
193
                // Base path
194
                if ($this->baseUri->getPath() !== '') {
195
                    $path = $this->baseUri->getPath().'/'.ltrim($uri->getPath(), '/');
196
                    $uri = $uri->withPath($path);
197
                }
198
            }
199
        }
200
201
        // Close connections to make sure invalidation (PURGE/BAN) requests
202
        // will not interfere with content (GET) requests.
203
        $request = $request->withUri($uri)->withHeader('Connection', 'Close');
204
205
        // Create a request to each caching proxy server
206
        foreach ($this->servers as $server) {
207
            $requests[] = $request->withUri(
208
                $uri
209
                    ->withScheme($server->getScheme())
210
                    ->withHost($server->getHost())
211
                    ->withPort($server->getPort()),
212
                true    // Preserve application Host header
213
            );
214
        }
215
216
        return $requests;
217
    }
218
219
    /**
220
     * Set caching proxy server URI objects, validating them.
221
     *
222
     * @param string[] $servers Caching proxy proxy server hostnames or IP
223
     *                          addresses, including port if not port 80.
224
     *                          E.g. ['127.0.0.1:6081']
225
     *
226
     * @throws InvalidUrlException If server is invalid or contains URL
227
     *                             parts other than scheme, host, port
228
     */
229
    private function setServers(array $servers)
230
    {
231
        $this->servers = [];
232
        foreach ($servers as $server) {
233
            $this->servers[] = $this->filterUri($server, ['scheme', 'host', 'port']);
234
        }
235
    }
236
237
    /**
238
     * Set application base URI that will be prefixed to relative purge and
239
     * refresh requests, and validate it.
240
     *
241
     * @param string $uriString Your application’s base URI
242
     *
243
     * @throws InvalidUrlException If the base URI is not a valid URI
244
     */
245
    private function setBaseUri($uriString = null)
246
    {
247
        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...
248
            $this->baseUri = null;
249
250
            return;
251
        }
252
253
        $this->baseUri = $this->filterUri($uriString);
254
    }
255
256
    /**
257
     * Filter a URL.
258
     *
259
     * Prefix the URL with "http://" if it has no scheme, then check the URL
260
     * for validity. You can specify what parts of the URL are allowed.
261
     *
262
     * @param string   $uriString
263
     * @param string[] $allowedParts Array of allowed URL parts (optional)
264
     *
265
     * @return UriInterface Filtered URI (with default scheme if there was no scheme)
266
     *
267
     * @throws InvalidUrlException If URL is invalid, the scheme is not http or
268
     *                             contains parts that are not expected
269
     */
270
    private function filterUri($uriString, array $allowedParts = [])
271
    {
272
        if (!is_string($uriString)) {
273
            throw new \InvalidArgumentException(sprintf(
274
                'URI parameter must be a string, %s given',
275
                gettype($uriString)
276
            ));
277
        }
278
279
        // Creating a PSR-7 URI without scheme (with parse_url) results in the
280
        // original hostname to be seen as path. So first add a scheme if none
281
        // is given.
282
        if (false === strpos($uriString, '://')) {
283
            $uriString = sprintf('%s://%s', 'http', $uriString);
284
        }
285
286
        try {
287
            $uri = $this->uriFactory->createUri($uriString);
288
        } catch (\InvalidArgumentException $e) {
289
            throw InvalidUrlException::invalidUrl($uriString);
290
        }
291
292
        if (!$uri->getScheme()) {
293
            throw InvalidUrlException::invalidUrl($uriString, 'empty scheme');
294
        }
295
296
        if (count($allowedParts) > 0) {
297
            $parts = parse_url((string) $uri);
298
            $diff = array_diff(array_keys($parts), $allowedParts);
299
            if (count($diff) > 0) {
300
                throw InvalidUrlException::invalidUrlParts($uriString, $allowedParts);
301
            }
302
        }
303
304
        return $uri;
305
    }
306
307
    /**
308
     * Build a request signature based on the request data. Unique for every different request, identical
309
     * for the same requests.
310
     *
311
     * This signature is used to avoid sending the same invalidation request twice.
312
     *
313
     * @param RequestInterface $request An invalidation request
314
     *
315
     * @return string A signature for this request
316
     */
317
    private function getRequestSignature(RequestInterface $request)
318
    {
319
        $headers = $request->getHeaders();
320
        ksort($headers);
321
322
        return sha1($request->getMethod()."\n".$request->getUri()."\n".var_export($headers, true));
323
    }
324
}
325