1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\JsonReference\Loader; |
4
|
|
|
|
5
|
|
|
use League\JsonReference; |
6
|
|
|
use League\JsonReference\Decoder\JsonDecoder; |
7
|
|
|
use League\JsonReference\DecoderInterface; |
8
|
|
|
use League\JsonReference\LoaderInterface; |
9
|
|
|
|
10
|
|
|
final class CurlWebLoader implements LoaderInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var string |
14
|
|
|
*/ |
15
|
|
|
private $prefix; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var array |
19
|
|
|
*/ |
20
|
|
|
private $curlOptions; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var DecoderInterface |
24
|
|
|
*/ |
25
|
|
|
private $jsonDecoder; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param string $prefix |
29
|
|
|
* @param array $curlOptions |
30
|
|
|
* @param DecoderInterface $jsonDecoder |
31
|
|
|
*/ |
32
|
66 |
|
public function __construct($prefix, array $curlOptions = null, DecoderInterface $jsonDecoder = null) |
33
|
|
|
{ |
34
|
66 |
|
$this->prefix = $prefix; |
35
|
66 |
|
$this->jsonDecoder = $jsonDecoder ?: new JsonDecoder(); |
36
|
66 |
|
$this->setCurlOptions($curlOptions); |
37
|
66 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* {@inheritdoc} |
41
|
|
|
*/ |
42
|
14 |
|
public function load($path) |
43
|
|
|
{ |
44
|
14 |
|
$uri = $this->prefix . $path; |
45
|
14 |
|
$ch = curl_init($uri); |
46
|
14 |
|
curl_setopt_array($ch, $this->curlOptions); |
47
|
14 |
|
list($response, $statusCode) = $this->getResponseBodyAndStatusCode($ch); |
48
|
14 |
|
curl_close($ch); |
49
|
|
|
|
50
|
14 |
|
if ($statusCode >= 400 || !$response) { |
51
|
4 |
|
throw JsonReference\SchemaLoadingException::create($uri); |
52
|
|
|
} |
53
|
|
|
|
54
|
10 |
|
return $this->jsonDecoder->decode($response); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param resource $ch |
59
|
|
|
* |
60
|
|
|
* @return array |
61
|
|
|
*/ |
62
|
14 |
|
private function getResponseBodyAndStatusCode($ch) |
63
|
|
|
{ |
64
|
14 |
|
$response = curl_exec($ch); |
65
|
14 |
|
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
66
|
|
|
|
67
|
14 |
|
return [$response, $statusCode]; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return array |
72
|
|
|
*/ |
73
|
66 |
|
private function getDefaultCurlOptions() |
74
|
|
|
{ |
75
|
|
|
return [ |
76
|
66 |
|
CURLOPT_RETURNTRANSFER => true, |
77
|
66 |
|
CURLOPT_FOLLOWLOCATION => true, |
78
|
66 |
|
CURLOPT_MAXREDIRS => 20, |
79
|
33 |
|
]; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @param array|null $curlOptions |
84
|
|
|
*/ |
85
|
66 |
|
private function setCurlOptions($curlOptions) |
86
|
|
|
{ |
87
|
66 |
|
if (is_array($curlOptions)) { |
88
|
2 |
|
$this->curlOptions = $curlOptions + $this->getDefaultCurlOptions(); |
89
|
2 |
|
return; |
90
|
|
|
} |
91
|
|
|
|
92
|
64 |
|
$this->curlOptions = $this->getDefaultCurlOptions(); |
93
|
64 |
|
} |
94
|
|
|
} |
95
|
|
|
|