This repository has been archived by the owner on Apr 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fetch.php
93 lines (74 loc) · 2.33 KB
/
Fetch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace Faxity\Fetch;
/**
* Send HTTP requests via cURL
*/
class Fetch
{
/**
* Initializes a curl request
* @param string $url URL to send request to
* @param mixed $params Optional query parameters as an array or object
*
* @return resource|bool
*/
private function initRequest(string $url, $params)
{
if ($params) {
$query = "";
if (is_object($params) || is_array($params)) {
$query = http_build_query($params);
$url .= $query ? "?$query" : "";
}
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return $curl;
}
/**
* Sends a GET request to URL
* @param string $url URL to send request to
* @param mixed $params Optional query parameters as an array or object
*
* @return object
*/
public function get(string $url, $params = null) : ?object
{
$curl = self::initRequest($url, $params);
$body = curl_exec($curl);
curl_close($curl);
// Parse response as json
return json_decode($body);
}
/**
* Sends multiple GET requests in parallell
* @param array $requests An array of assoc-arrays with url and params as keys, like:
* [
* "url" => "",
* "params" => [ "param" => "" ]
* ]
*/
public function getMulti(array $requests)
{
$multi = curl_multi_init();
// Create handles for cURL request
$handles = array_map(function ($item) use ($multi) {
$handle = self::initRequest($item["url"], $item["params"] ?? null);
curl_multi_add_handle($multi, $handle);
return $handle;
}, $requests);
// Execute requests in parallell and wait for all to complete
do {
$status = curl_multi_exec($multi, $active);
$active && curl_multi_select($multi); // Prevents CPU overusage
} while ($active && $status == CURLM_OK);
// Cleanup and get content
$content = array_map(function ($handle) use ($multi) {
curl_multi_remove_handle($multi, $handle);
$body = curl_multi_getcontent($handle);
return json_decode($body);
}, $handles);
curl_multi_close($multi);
return $content;
}
}