-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGoogle_Client_Multi.php
125 lines (111 loc) · 2.41 KB
/
Google_Client_Multi.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?php
use Psr\Http\Message\RequestInterface;
/**
* @author Igor Belikov <[email protected]>
*/
class Google_Client_Multi_Exception extends Exception {}
class Google_Service_Multi extends Google_Service
{
}
/**
* Google Client Wrapper for using multi project keys
* @author Igor Belikov <[email protected]>
*/
class Google_Client_Multi extends Google_Client
{
/**
* @var array
*/
private $multiConfig = array();
/**
* @var string
*/
private $currentDeveloperKey = '';
/**
* @var int
*/
private $currentDeveloperKeyIndex = 0;
/**
* @param array $keys
* @return $this
*/
public function setKeys(array $keys)
{
$this->multiConfig['developerKeys'] = $keys;
return $this;
}
/**
* @param array $config
* @return $this
*/
public function setMultiConfig(array $config)
{
$this->multiConfig = $config;
return $this;
}
/**
* @return string
*/
private function getDeveloperKey()
{
return $this->currentDeveloperKey;
}
/**
* @return array
*/
private function getDeveloperKeys()
{
return $this->multiConfig['developerKeys'];
}
/**
* Set next "Developer Key" from config
* @return string
* @throws Google_Client_Multi_Exception
*/
private function setNextDeveloperKey()
{
if($this->currentDeveloperKey) {
$this->currentDeveloperKeyIndex++;
}
$keys = $this->getDeveloperKeys();
if(isset($keys[$this->currentDeveloperKeyIndex])) {
$this->currentDeveloperKey = $keys[$this->currentDeveloperKeyIndex];
$this->setDeveloperKey($this->currentDeveloperKey);
return $this->currentDeveloperKey;
} else {
throw new Google_Client_Multi_Exception("No more keys :|");
}
}
/**
* Prepare client
* @return $this
*/
public function prepareMulti()
{
$this->setNextDeveloperKey();
return $this;
}
/**
* @override
* @param RequestInterface $request
* @param null $expectedClass
* @return object
* @throws Google_Client_Multi_Exception
* @throws Google_Service_Exception
*/
public function execute($request, $expectedClass = null)
{
try {
$result = parent::execute($request, $expectedClass);
} catch(Google_Service_Exception $e) {
$errors = $e->getErrors();
if($e->getCode() == 403 && isset($errors[0]['reason']) && $errors[0]['reason'] == 'dailyLimitExceeded') {
$request->setQueryParam('key', $this->setNextDeveloperKey());
$result = $this->execute($request);
} else {
throw $e;
}
}
return $result;
}
}