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
|
|
|
/** |
41
|
|
|
* Function that takes multiple api urls and returns the result as a decoded json. |
42
|
|
|
* |
43
|
|
|
* @param array $urls |
44
|
|
|
* |
45
|
|
|
* @return array $result |
46
|
|
|
*/ |
47
|
2 |
|
public function multi(Array $urls) : array |
48
|
|
|
{ |
49
|
|
|
// Setup options |
50
|
|
|
$options = [ |
51
|
2 |
|
CURLOPT_RETURNTRANSFER => true, |
52
|
2 |
|
CURLOPT_HEADER => 0, |
53
|
|
|
]; |
54
|
|
|
// Add all curl handlers and remember them |
55
|
|
|
// Initiate the multi curl handler |
56
|
2 |
|
$mh = curl_multi_init(); |
57
|
2 |
|
$chAll = []; |
58
|
2 |
|
foreach ($urls as $url) { |
59
|
2 |
|
$ch = curl_init($url); |
60
|
2 |
|
curl_setopt_array($ch, $options); |
|
|
|
|
61
|
2 |
|
curl_multi_add_handle($mh, $ch); |
|
|
|
|
62
|
2 |
|
$chAll[] = $ch; |
63
|
|
|
} |
64
|
|
|
// Execute all queries simultaneously, |
65
|
|
|
// and continue when all are complete |
66
|
2 |
|
$running = null; |
67
|
|
|
do { |
68
|
2 |
|
curl_multi_exec($mh, $running); |
69
|
2 |
|
} while ($running); |
70
|
|
|
// Close the handles |
71
|
2 |
|
foreach ($chAll as $ch) { |
72
|
2 |
|
curl_multi_remove_handle($mh, $ch); |
73
|
|
|
} |
74
|
2 |
|
curl_multi_close($mh); |
75
|
|
|
// All of our requests are done, we can now access the results |
76
|
2 |
|
$response = []; |
77
|
2 |
|
foreach ($chAll as $ch) { |
78
|
2 |
|
$data = curl_multi_getcontent($ch); |
79
|
2 |
|
$response[] = json_decode($data, true); |
80
|
|
|
} |
81
|
2 |
|
return $response; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|