Completed
Pull Request — master (#312)
by David
06:00
created

HttpDispatcher::setBaseUri()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
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 38
    public function __construct(
83
        array $servers,
84
        $baseUri = '',
85
        HttpAsyncClient $httpClient = null,
86
        UriFactory $uriFactory = null
87
    ) {
88 38
        $this->httpClient = $httpClient ?: HttpAsyncClientDiscovery::find();
89 38
        $this->uriFactory = $uriFactory ?: UriFactoryDiscovery::find();
90
91 38
        $this->setServers($servers);
92 35
        $this->setBaseUri($baseUri);
93 34
    }
94
95
    /**
96
     * Queue invalidation request.
97
     *
98
     * @param RequestInterface $invalidationRequest
99
     */
100 32
    public function invalidate(RequestInterface $invalidationRequest)
101
    {
102 32
        if (!$this->baseUri && !$invalidationRequest->getUri()->getHost()) {
103 1
            throw MissingHostException::missingHost((string) $invalidationRequest->getUri());
104
        }
105
106 31
        $signature = $this->getRequestSignature($invalidationRequest);
107
108 31
        if (isset($this->queue[$signature])) {
109 1
            return;
110
        }
111
112 31
        $this->queue[$signature] = $invalidationRequest;
113 31
    }
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 32
    public function flush()
123
    {
124 32
        $queue = $this->queue;
125 32
        $this->queue = [];
126
        /** @var Promise[] $promises */
127 32
        $promises = [];
128
129 32
        $exceptions = new ExceptionCollection();
130
131 32
        foreach ($queue as $request) {
132 31
            foreach ($this->fanOut($request) as $proxyRequest) {
133
                try {
134 31
                    $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
135 31
                } catch (\Exception $e) {
136 1
                    $exceptions->add(new InvalidArgumentException($e));
137
                }
138 31
            }
139 32
        }
140
141 32
        foreach ($promises as $promise) {
142
            try {
143 31
                $promise->wait();
144 31
            } catch (HttpException $exception) {
145 1
                $exceptions->add(ProxyResponseException::proxyResponse($exception->getResponse()));
146 2
            } catch (RequestException $exception) {
147 1
                $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
148 1
            } catch (\Exception $exception) {
149
                // @codeCoverageIgnoreStart
150
                $exceptions->add(new InvalidArgumentException($exception));
151
                // @codeCoverageIgnoreEnd
152
            }
153 32
        }
154
155 32
        if (count($exceptions)) {
156 3
            throw $exceptions;
157
        }
158
159 32
        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 31
    private function fanOut(RequestInterface $request)
170
    {
171 31
        $requests = [];
172
173 31
        $uri = $request->getUri();
174
175
        // If a base URI is configured, try to make partial invalidation
176
        // requests complete.
177 31
        if ($this->baseUri) {
178 31
            if ($uri->getHost()) {
179
                // Absolute URI: does it already have a scheme?
180 5
                if (!$uri->getScheme() && $this->baseUri->getScheme() !== '') {
181 1
                    $uri = $uri->withScheme($this->baseUri->getScheme());
182 1
                }
183 5
            } else {
184
                // Relative URI
185 26
                if ($this->baseUri->getHost() !== '') {
186 26
                    $uri = $uri->withHost($this->baseUri->getHost());
187 26
                }
188
189 26
                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 17
                    $uri = $uri->withPort($this->baseUri->getPort());
191 17
                }
192
193
                // Base path
194 26
                if ($this->baseUri->getPath() !== '') {
195 1
                    $path = $this->baseUri->getPath().'/'.ltrim($uri->getPath(), '/');
196 1
                    $uri = $uri->withPath($path);
197 1
                }
198
            }
199 31
        }
200
201
        // Close connections to make sure invalidation (PURGE/BAN) requests
202
        // will not interfere with content (GET) requests.
203 31
        $request = $request->withUri($uri)->withHeader('Connection', 'Close');
204
205
        // Create a request to each caching proxy server
206 31
        foreach ($this->servers as $server) {
207 31
            $requests[] = $request->withUri(
208
                $uri
209 31
                    ->withScheme($server->getScheme())
210 31
                    ->withHost($server->getHost())
211 31
                    ->withPort($server->getPort()),
212
                true    // Preserve application Host header
213 31
            );
214 31
        }
215
216 31
        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 38
    private function setServers(array $servers)
230
    {
231 38
        $this->servers = [];
232 38
        foreach ($servers as $server) {
233 38
            $this->servers[] = $this->filterUri($server, ['scheme', 'host', 'port']);
234 35
        }
235 35
    }
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 35
    private function setBaseUri($uriString = null)
246
    {
247 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...
248 1
            $this->baseUri = null;
249
250 1
            return;
251
        }
252
253 34
        $this->baseUri = $this->filterUri($uriString);
254 33
    }
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 38
    private function filterUri($uriString, array $allowedParts = [])
271
    {
272 38
        if (!is_string($uriString)) {
273 1
            throw new \InvalidArgumentException(sprintf(
274 1
                'URI parameter must be a string, %s given',
275 1
                gettype($uriString)
276 1
            ));
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 38
        if (false === strpos($uriString, '://')) {
283 35
            $uriString = sprintf('%s://%s', 'http', $uriString);
284 35
        }
285
286
        try {
287 38
            $uri = $this->uriFactory->createUri($uriString);
288 38
        } catch (\InvalidArgumentException $e) {
289 1
            throw InvalidUrlException::invalidUrl($uriString);
290
        }
291
292 37
        if (!$uri->getScheme()) {
293 1
            throw InvalidUrlException::invalidUrl($uriString, 'empty scheme');
294
        }
295
296 36
        if (count($allowedParts) > 0) {
297 36
            $parts = parse_url((string) $uri);
298 36
            $diff = array_diff(array_keys($parts), $allowedParts);
299 36
            if (count($diff) > 0) {
300 1
                throw InvalidUrlException::invalidUrlParts($uriString, $allowedParts);
301
            }
302 35
        }
303
304 35
        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 31
    private function getRequestSignature(RequestInterface $request)
318
    {
319 31
        $headers = $request->getHeaders();
320 31
        ksort($headers);
321
322 31
        return sha1($request->getMethod()."\n".$request->getUri()."\n".var_export($headers, true));
323
    }
324
}
325