1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nihl\RemoteService; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* A model class for handling curl requests |
7
|
|
|
* |
8
|
|
|
* @SuppressWarnings(PHPMD.ShortVariable) |
9
|
|
|
*/ |
10
|
|
|
class Curl |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Do curl request |
14
|
|
|
* |
15
|
|
|
* @param string $url |
16
|
|
|
* |
17
|
|
|
* @return string |
18
|
|
|
*/ |
19
|
1 |
|
public function doRequest(string $url) |
20
|
|
|
{ |
21
|
|
|
// Initiate curl handler |
22
|
1 |
|
$ch = curl_init(); |
23
|
|
|
|
24
|
|
|
// Will return the response, if false it print the response |
25
|
1 |
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
|
|
|
26
|
|
|
|
27
|
|
|
// Set the url |
28
|
1 |
|
curl_setopt($ch, CURLOPT_URL, $url); |
29
|
|
|
|
30
|
|
|
// Execute |
31
|
1 |
|
$data = curl_exec($ch); |
|
|
|
|
32
|
|
|
|
33
|
|
|
// Closing |
34
|
1 |
|
curl_close($ch); |
|
|
|
|
35
|
|
|
|
36
|
1 |
|
return $data; |
|
|
|
|
37
|
|
|
// return json_decode($data, true); |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
public function doMultiRequest(array $urls) |
41
|
|
|
{ |
42
|
|
|
$options = [ |
43
|
1 |
|
CURLOPT_RETURNTRANSFER => true, |
44
|
|
|
]; |
45
|
|
|
|
46
|
|
|
// Add all curl handlers and remember them |
47
|
|
|
// Initiate the multi curl handler |
48
|
1 |
|
$mh = curl_multi_init(); |
49
|
1 |
|
$chAll = []; |
50
|
1 |
|
foreach ($urls as $url) { |
51
|
1 |
|
$ch = curl_init("$url"); |
52
|
|
|
// $ch = curl_init("$url/$id"); |
53
|
1 |
|
curl_setopt_array($ch, $options); |
|
|
|
|
54
|
1 |
|
curl_multi_add_handle($mh, $ch); |
|
|
|
|
55
|
1 |
|
$chAll[] = $ch; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// Execute all queries simultaneously, |
59
|
|
|
// and continue when all are complete |
60
|
1 |
|
$running = null; |
61
|
|
|
do { |
62
|
1 |
|
curl_multi_exec($mh, $running); |
63
|
1 |
|
} while ($running); |
64
|
|
|
|
65
|
|
|
// Close the handles |
66
|
1 |
|
foreach ($chAll as $ch) { |
67
|
1 |
|
curl_multi_remove_handle($mh, $ch); |
68
|
|
|
} |
69
|
1 |
|
curl_multi_close($mh); |
70
|
|
|
|
71
|
|
|
// All of our requests are done, we can now access the results |
72
|
1 |
|
$response = []; |
73
|
1 |
|
foreach ($chAll as $ch) { |
74
|
1 |
|
$data = curl_multi_getcontent($ch); |
75
|
1 |
|
$response[] = json_decode($data, true); |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
return $response; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|