1
|
|
|
<?php |
2
|
|
|
namespace Perry\Fetcher; |
3
|
|
|
|
4
|
|
|
use Perry\Cache\CacheManager; |
5
|
|
|
use Perry\Perry; |
6
|
|
|
use Perry\Response; |
7
|
|
|
use Perry\Setup; |
8
|
|
|
use Perry\Tool; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class FileFetcher |
12
|
|
|
* |
13
|
|
|
* @package Perry\Fetcher |
14
|
|
|
* @deprecated |
15
|
|
|
*/ |
16
|
|
|
class FileFetcher implements CanFetch |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* form the opts array |
21
|
|
|
* |
22
|
|
|
* @param string $representation |
23
|
|
|
* @return array |
24
|
|
|
*/ |
25
|
|
|
private function getOpts($representation) |
26
|
|
|
{ |
27
|
|
|
$opts = array( |
28
|
|
|
'http' => array( |
29
|
|
|
'method' => "GET", |
30
|
|
|
), |
31
|
|
|
'socket' => [ |
32
|
|
|
'bindto' => Setup::$bindToIp |
33
|
|
|
] |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
if (is_null($representation)) { |
37
|
|
|
$header = "Accept-language: en\r\nUser-Agent: Perry/".Perry::$version.' '.Setup::$userAgent."\r\n"; |
38
|
|
|
} else { |
39
|
|
|
$header = "Accept-language: en\r\nUser-Agent: Perry/". |
40
|
|
|
Perry::$version.' '.Setup::$userAgent."\r\nAccept: application/$representation+json\r\n"; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$opts['http']['header'] = $header; |
44
|
|
|
|
45
|
|
|
$opts = array_merge_recursive(Setup::$fetcherOptions, $opts); |
46
|
|
|
|
47
|
|
|
return $opts; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param string $url |
52
|
|
|
* @param string $representation |
53
|
|
|
* @throws \Exception |
54
|
|
|
* @return \Perry\Response |
55
|
|
|
*/ |
56
|
|
|
public function doGetRequest($url, $representation) |
57
|
|
|
{ |
58
|
|
|
|
59
|
|
|
if ($data = CacheManager::getInstance()->load($url)) { |
60
|
|
|
return new Response($data['value'], $data['representation']); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$context = stream_context_create($this->getOpts($representation)); |
64
|
|
|
|
65
|
|
|
if (false === ($data = @file_get_contents($url, false, $context))) { |
66
|
|
|
|
67
|
|
|
if (false === $headers = (@get_headers($url, 1))) { |
68
|
|
|
throw new \Exception("could not connect to api"); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
throw new \Exception("an error occured with the http request: ".$headers[0]); |
72
|
|
|
} else { |
73
|
|
|
$headers = @get_headers($url, 1); |
74
|
|
|
if (isset($headers['Content-Type'])) { |
75
|
|
|
if (false !== ($retrep = Tool::parseContentTypeToRepresentation($headers['Content-Type']))) { |
76
|
|
|
$representation = $retrep; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
CacheManager::getInstance()->save($url, ["representation" => $representation, "value" => $data]); |
83
|
|
|
|
84
|
|
|
return new Response($data, $representation); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|