1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
//---------------------------------------------------------------------- |
4
|
|
|
// |
5
|
|
|
// Copyright (C) 2015 Artem Rodygin |
6
|
|
|
// |
7
|
|
|
// This file is part of Linode API Client Library for PHP. |
8
|
|
|
// |
9
|
|
|
// You should have received a copy of the MIT License along with |
10
|
|
|
// the library. If not, see <http://opensource.org/licenses/MIT>. |
11
|
|
|
// |
12
|
|
|
//---------------------------------------------------------------------- |
13
|
|
|
|
14
|
|
|
namespace Linode; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* A batch of requests. |
18
|
|
|
*/ |
19
|
|
|
class Batch |
20
|
|
|
{ |
21
|
|
|
/** @var string API key */ |
22
|
|
|
protected $key; |
23
|
|
|
|
24
|
|
|
/** @var array Batched requests */ |
25
|
|
|
protected $requests; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Constructor. |
29
|
|
|
* |
30
|
|
|
* @param string $key |
31
|
|
|
*/ |
32
|
1 |
|
public function __construct($key) |
33
|
|
|
{ |
34
|
1 |
|
$this->key = $key; |
35
|
1 |
|
$this->requests = []; |
36
|
1 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Adds specified request to the batch. |
40
|
|
|
* |
41
|
|
|
* @param array $query Request parameters |
42
|
|
|
*/ |
43
|
1 |
|
public function addRequest($query) |
44
|
|
|
{ |
45
|
1 |
|
$this->requests[] = $query; |
46
|
1 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Performs a call for currently batched requests. |
50
|
|
|
* |
51
|
|
|
* @param bool $debug Whether make a call in a debug mode |
52
|
|
|
* |
53
|
|
|
* @throws \Exception |
54
|
|
|
* |
55
|
|
|
* @return array|string|false Array of results (or query string in debug mode) |
56
|
|
|
*/ |
57
|
1 |
|
public function execute($debug = false) |
58
|
|
|
{ |
59
|
1 |
|
if (count($this->requests) === 0) { |
60
|
1 |
|
return false; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
$curl = curl_init(); |
64
|
|
|
|
65
|
1 |
|
if (!$curl) { |
|
|
|
|
66
|
|
|
return false; |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
$query = "api_key={$this->key}&api_action=batch&api_requestArray=" . json_encode($this->requests); |
70
|
|
|
|
71
|
1 |
|
$this->requests = []; |
72
|
|
|
|
73
|
1 |
|
if ($debug) { |
74
|
1 |
|
return $query; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
curl_setopt($curl, CURLOPT_URL, 'https://api.linode.com/'); |
78
|
|
|
curl_setopt($curl, CURLOPT_POST, true); |
79
|
|
|
curl_setopt($curl, CURLOPT_POSTFIELDS, $query); |
80
|
|
|
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); |
81
|
|
|
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); |
82
|
|
|
|
83
|
|
|
$result = curl_exec($curl); |
84
|
|
|
|
85
|
|
|
curl_close($curl); |
86
|
|
|
|
87
|
|
|
$json = json_decode($result, true); |
88
|
|
|
|
89
|
|
|
if (!$json) { |
90
|
|
|
throw new \RuntimeException('Empty response'); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
return $json; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|