1
|
|
|
<?php |
2
|
|
|
namespace Perry\Fetcher; |
3
|
|
|
|
4
|
|
|
use GuzzleHttp\Client; |
5
|
|
|
use Perry\Cache\CacheManager; |
6
|
|
|
use Perry\Perry; |
7
|
|
|
use Perry\Response; |
8
|
|
|
use Perry\Setup; |
9
|
|
|
use Perry\Tool; |
10
|
|
|
|
11
|
|
|
class GuzzleFetcher implements CanFetch |
12
|
|
|
{ |
13
|
|
|
private $guzzle; |
14
|
|
|
|
15
|
|
|
public function __construct() |
16
|
|
|
{ |
17
|
|
|
$this->guzzle = new Client(); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* form the opts array |
22
|
|
|
* |
23
|
|
|
* @param string $representation |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
|
|
private function getOpts($representation) |
27
|
|
|
{ |
28
|
|
|
$headers = [ |
29
|
|
|
"Accept-language" => "en", |
30
|
|
|
'User-Agent' => 'Perry/' . Perry::$version . ' ' .Setup::$userAgent |
31
|
|
|
]; |
32
|
|
|
|
33
|
|
|
if (!is_null($representation)) { |
34
|
|
|
$headers["Accept"] = "application/$representation+json"; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$config =[]; |
38
|
|
|
|
39
|
|
|
if ("0.0.0.0:0" != Setup::$bindToIp) { |
40
|
|
|
$config['curl'] = [CURLOPT_INTERFACE => Setup::$bindToIp]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$options = [ |
44
|
|
|
"headers" => $headers, |
45
|
|
|
"config" => $config |
46
|
|
|
]; |
47
|
|
|
|
48
|
|
|
// merge in the ons from the options array |
49
|
|
|
$options = array_merge_recursive(Setup::$fetcherOptions, $options); |
50
|
|
|
|
51
|
|
|
return $options; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param string $url |
56
|
|
|
* @param string $representation |
57
|
|
|
* @throws \Exception |
58
|
|
|
* @return \Perry\Response |
59
|
|
|
*/ |
60
|
|
|
public function doGetRequest($url, $representation) |
61
|
|
|
{ |
62
|
|
|
|
63
|
|
|
if ($data = CacheManager::getInstance()->load($url)) { |
64
|
|
|
return new Response($data['value'], $data['representation']); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$response = $this->guzzle->get($url, $this->getOpts($representation)); |
68
|
|
|
|
69
|
|
|
$data = $response->getBody(); |
70
|
|
|
$data = (String) $data; |
71
|
|
|
|
72
|
|
|
if ($response->hasHeader("Content-Type")) { |
73
|
|
|
if (false !== ($retrep = Tool::parseContentTypeToRepresentation($response->getHeader("Content-Type")))) { |
|
|
|
|
74
|
|
|
$representation = $retrep; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
CacheManager::getInstance()->save($url, ["representation" => $representation, "value" => $data]); |
79
|
|
|
|
80
|
|
|
return new Response($data, $representation); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
This check looks at variables that are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.