chrisaugustsson /
weatherService
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Anax\Curl; |
||
| 4 | |||
| 5 | class Curl |
||
| 6 | { |
||
| 7 | private $cache; |
||
| 8 | |||
| 9 | 1 | public function __construct($cache) |
|
| 10 | { |
||
| 11 | 1 | $this->cache = $cache; |
|
| 12 | 1 | } |
|
| 13 | |||
| 14 | |||
| 15 | 1 | public function get(string $url) |
|
| 16 | { |
||
| 17 | 1 | $cache = $this->cache; |
|
| 18 | |||
| 19 | 1 | $cleanUrl = preg_replace('/[^A-Za-z0-9\-]/', '', $url); |
|
| 20 | |||
| 21 | 1 | if ($cache->get($cleanUrl)) { |
|
| 22 | 1 | return json_decode($cache->get($cleanUrl)); |
|
| 23 | } |
||
| 24 | |||
| 25 | $ch = curl_init(); |
||
| 26 | curl_setopt($ch, CURLOPT_URL, $url); |
||
| 27 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
||
| 28 | $res = curl_exec($ch); |
||
| 29 | curl_close($ch); |
||
| 30 | |||
| 31 | $cache->set($cleanUrl, $res); |
||
| 32 | |||
| 33 | return json_decode($res); |
||
| 34 | } |
||
| 35 | |||
| 36 | public function getMulti(array $urls) |
||
| 37 | { |
||
| 38 | $res = []; |
||
| 39 | $mh = curl_multi_init(); |
||
| 40 | |||
| 41 | foreach ($urls as $key => $value) { |
||
| 42 | $multiCurl[$key] = curl_init(); |
||
| 43 | curl_setopt($multiCurl[$key], CURLOPT_URL, $urls[$key]); |
||
|
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
Loading history...
|
|||
| 44 | curl_setopt($multiCurl[$key], CURLOPT_RETURNTRANSFER, 1); |
||
| 45 | curl_multi_add_handle($mh, $multiCurl[$key]); |
||
| 46 | } |
||
| 47 | |||
| 48 | $index = null; |
||
| 49 | do { |
||
| 50 | curl_multi_exec($mh, $index); |
||
| 51 | } while ($index > 0); |
||
| 52 | |||
| 53 | foreach ($multiCurl as $k => $ch) { |
||
| 54 | $res[$k] = json_decode(curl_multi_getcontent($ch)); |
||
| 55 | curl_multi_remove_handle($mh, $ch); |
||
| 56 | } |
||
| 57 | |||
| 58 | curl_multi_close($mh); |
||
| 59 | |||
| 60 | return $res; |
||
| 61 | } |
||
| 62 | } |
||
| 63 |