-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathFallbackRemoteGetRequest.php
More file actions
83 lines (73 loc) · 2.78 KB
/
FallbackRemoteGetRequest.php
File metadata and controls
83 lines (73 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace AmpProject\RemoteRequest;
use AmpProject\Exception\FailedRemoteRequest;
use AmpProject\RemoteGetRequest;
use AmpProject\Response;
use Exception;
/**
* Fallback pipeline implementation to go through a series of fallback requests until a request succeeds.
*
* The request will be tried with the first instance provided, and follow the instance series from one to the next until
* a successful response was returned.
*
* A successful response is a response that doesn't return boolean false and doesn't throw an exception.
*
* @package ampproject/amp-toolbox
*/
final class FallbackRemoteGetRequest implements RemoteGetRequest
{
/**
* Array of RemoteGetRequest instances to churn through.
*
* @var RemoteGetRequest[]
*/
private $pipeline;
/**
* Instantiate a FallbackRemoteGetRequest object.
*
* @param RemoteGetRequest ...$pipeline Variadic array of RemoteGetRequest instances to use as consecutive
* fallbacks.
*/
public function __construct(RemoteGetRequest ...$pipeline)
{
array_walk($pipeline, [$this, 'addRemoteGetRequestInstance']);
}
/**
* Add a single RemoteGetRequest instance to the pipeline.
*
* This adds strong typing to the variadic $pipeline argument in the constructor.
*
* @param RemoteGetRequest $remoteGetRequest RemoteGetRequest instance to the pipeline.
*/
private function addRemoteGetRequestInstance(RemoteGetRequest $remoteGetRequest)
{
$this->pipeline[] = $remoteGetRequest;
}
/**
* Do a GET request to retrieve the contents of a remote URL.
*
* @param string $url URL to get.
* @param array $headers Optional. Associative array of headers to send with the request. Defaults to empty array.
* @return Response Response for the executed request.
* @throws FailedRemoteRequest If retrieving the contents from the URL failed.
*/
public function get($url, $headers = [])
{
foreach ($this->pipeline as $remoteGetRequest) {
try {
$response = $remoteGetRequest->get($url, $headers);
if (! $response instanceof RemoteGetRequestResponse) {
continue;
}
$statusCode = $response->getStatusCode();
if (200 <= $statusCode && $statusCode < 300) {
return $response;
}
} catch (Exception $exception) {
// Don't let exceptions bubble up, just continue with the next instance in the pipeline.
}
}
// @todo Not sure what status code to use here. "503 Service Unavailable" is a temporary server-side error.
return new RemoteGetRequestResponse('', [], 503);
}
}