-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathFilesystemRemoteGetRequest.php
More file actions
66 lines (59 loc) · 2.21 KB
/
Copy pathFilesystemRemoteGetRequest.php
File metadata and controls
66 lines (59 loc) · 2.21 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
<?php
namespace AmpProject\RemoteRequest;
use AmpProject\Exception\FailedToGetFromRemoteUrl;
use AmpProject\RemoteGetRequest;
use AmpProject\Response;
use Exception;
use LogicException;
/**
* Fetch the response for a remote request from the local filesystem instead.
*
* This can be used to provide offline fallbacks.
*
* @package ampproject/amp-toolbox
*/
final class FilesystemRemoteGetRequest implements RemoteGetRequest
{
/**
* Associative array of data for mapping between arguments and filepaths pointing to the results to return.
*
* @var array
*/
private $argumentMap;
/**
* Instantiate a FilesystemRemoteGetRequest object.
*
* @param array $argumentMap Associative array of data for mapping between arguments and filepaths pointing to the
* results to return.
*/
public function __construct($argumentMap)
{
$this->argumentMap = $argumentMap;
}
/**
* 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 FailedToGetFromRemoteUrl If retrieving the contents from the URL failed.
* @throws LogicException If invalid file path and/or invalid or non-readable file.
*/
public function get($url, $headers = [])
{
if (! array_key_exists($url, $this->argumentMap)) {
throw new LogicException("Trying to get a remote request from the filesystem for an unknown URL: {$url}.");
}
if (! file_exists($this->argumentMap[$url]) || ! is_readable($this->argumentMap[$url])) {
throw new LogicException(
'Trying to get a remote request from the filesystem for a file that is not accessible: '
. "{$url} => {$this->argumentMap[$url]}."
);
}
try {
return new RemoteGetRequestResponse(file_get_contents($this->argumentMap[$url]));
} catch (Exception $exception) {
throw FailedToGetFromRemoteUrl::withException($url, $exception);
}
}
}