1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Linder\Model; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* A model class retrievieng data from an external server. |
7
|
|
|
*/ |
8
|
|
|
class Curl |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Function that takes an api url and returns the result as a decoded json. |
12
|
|
|
* |
13
|
|
|
* @param string $url |
14
|
|
|
* |
15
|
|
|
* @return array $result |
16
|
|
|
*/ |
17
|
2 |
|
public function single(String $url) : array |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
// Setup options |
21
|
|
|
$options = [ |
22
|
2 |
|
CURLOPT_RETURNTRANSFER => true, |
23
|
2 |
|
CURLOPT_HEADER => 0, |
24
|
2 |
|
CURLOPT_URL => $url |
25
|
|
|
]; |
26
|
|
|
// Initiate curl handler |
27
|
2 |
|
$ch = curl_init(); |
28
|
|
|
// Set options |
29
|
2 |
|
curl_setopt_array($ch, $options); |
|
|
|
|
30
|
|
|
// Execute |
31
|
2 |
|
$data = curl_exec($ch); |
|
|
|
|
32
|
|
|
// Closing |
33
|
2 |
|
curl_close($ch); |
|
|
|
|
34
|
2 |
|
$res = json_decode($data, true); |
35
|
|
|
|
36
|
2 |
|
return $res; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Function that takes multiple api urls and returns the result as a decoded json. |
41
|
|
|
* |
42
|
|
|
* @param array $urls |
43
|
|
|
* |
44
|
|
|
* @return array $result |
45
|
|
|
*/ |
46
|
2 |
|
public function multi(Array $urls) : array |
47
|
|
|
{ |
48
|
|
|
// Setup options |
49
|
|
|
$options = [ |
50
|
2 |
|
CURLOPT_RETURNTRANSFER => true, |
51
|
2 |
|
CURLOPT_HEADER => 0, |
52
|
|
|
]; |
53
|
|
|
// Add all curl handlers and remember them |
54
|
|
|
// Initiate the multi curl handler |
55
|
2 |
|
$mh = curl_multi_init(); |
56
|
2 |
|
$chAll = []; |
57
|
2 |
|
foreach ($urls as $url) { |
58
|
2 |
|
$ch = curl_init($url); |
59
|
2 |
|
curl_setopt_array($ch, $options); |
|
|
|
|
60
|
2 |
|
curl_multi_add_handle($mh, $ch); |
|
|
|
|
61
|
2 |
|
$chAll[] = $ch; |
62
|
|
|
} |
63
|
|
|
// Execute all queries simultaneously, |
64
|
|
|
// and continue when all are complete |
65
|
2 |
|
$running = null; |
66
|
|
|
do { |
67
|
2 |
|
curl_multi_exec($mh, $running); |
68
|
2 |
|
} while ($running); |
69
|
|
|
// Close the handles |
70
|
2 |
|
foreach ($chAll as $ch) { |
71
|
2 |
|
curl_multi_remove_handle($mh, $ch); |
72
|
|
|
} |
73
|
2 |
|
curl_multi_close($mh); |
74
|
|
|
// All of our requests are done, we can now access the results |
75
|
2 |
|
$response = []; |
76
|
2 |
|
foreach ($chAll as $ch) { |
77
|
2 |
|
$data = curl_multi_getcontent($ch); |
78
|
2 |
|
$response[] = json_decode($data, true); |
79
|
|
|
} |
80
|
2 |
|
return $response; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|