forked from iron-io/iron_cache_php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IronCache.class.php
441 lines (390 loc) · 12.1 KB
/
IronCache.class.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<?php
/**
* PHP client for IronCache
*
* @link https://github.com/iron-io/iron_cache_php
* @link http://www.iron.io/products/cache
* @link http://dev.iron.io/
* @version 0.1.3
* @package IronCache
* @copyright Feel free to copy, steal, take credit for, or whatever you feel like doing with this code. ;)
*/
class IronCache_Item {
private $value;
private $expires_in;
private $replace;
private $add;
const max_expires_in = 2592000;
/**
* Create a new item.
*
* @param array|string $item
* An array of item properties or a string of the item value.
* Fields in item array:
* Required:
* - value: string - The item data, as a string.
* Optional:
* - expires_in: integer - How long in seconds to keep the item on the cache before it is deleted. Default is 604,800 seconds (7 days). Maximum is 2,592,000 seconds (30 days).
* - replace: boolean - Will only work if key already exists.
* - add: boolean - Will only work if key does not exist.
*/
function __construct($item) {
if(is_string($item) || is_integer($item)) {
$this->setValue($item);
} elseif(is_array($item)) {
$this->setValue($item['value']);
if(array_key_exists("replace", $item)) {
$this->setReplace($item['replace']);
}
if(array_key_exists("add", $item)) {
$this->setAdd($item['add']);
}
if(array_key_exists("expires_in", $item)) {
$this->setExpiresIn($item['expires_in']);
}
}
}
public function setValue($value) {
if ($value === null) {
throw new InvalidArgumentException("Please specify a value");
} else {
$this->value = $value;
}
}
public function getValue() {
return $this->value;
}
public function setReplace($replace) {
$this->replace = $replace;
}
public function getReplace() {
return $this->replace;
}
public function setAdd($add) {
$this->add = $add;
}
public function getAdd() {
return $this->add;
}
public function setExpiresIn($expires_in) {
if($expires_in > self::max_expires_in) {
throw new InvalidArgumentException("Expires In can't be greater than ".self::max_expires_in.".");
} else {
$this->expires_in = $expires_in;
}
}
public function getExpiresIn(){
return $this->expires_in;
}
public function asArray() {
$array = array();
$array['value'] = $this->getValue();
if($this->getExpiresIn() != null) {
$array['expires_in'] = $this->getExpiresIn();
}
if($this->getReplace() != null) {
$array['replace'] = $this->getReplace();
}
if($this->getAdd() != null) {
$array['add'] = $this->getAdd();
}
return $array;
}
}
class IronCache extends IronCore {
protected $client_version = '0.1.3';
protected $client_name = 'iron_cache_php';
protected $product_name = 'iron_cache';
protected $default_values = array(
'protocol' => 'https',
'host' => 'cache-aws-us-east-1.iron.io',
'port' => '443',
'api_version' => '1',
);
private $cache_name;
public $session_expire_time = 172800; # 2 days
/**
* @param string|array $config_file_or_options
* Array of options or name of config file.
* Fields in options array or in config:
*
* Required:
* - token
* - project_id
* Optional:
* - protocol
* - host
* - port
* - api_version
* @param string|null $cache_name set default cache name
*/
function __construct($config_file_or_options = null, $cache_name = null){
$this->getConfigData($config_file_or_options);
$this->url = "{$this->protocol}://{$this->host}:{$this->port}/{$this->api_version}/";
$this->setCacheName($cache_name);
}
/**
* Switch active project
*
* @param string $project_id Project ID
* @throws InvalidArgumentException
*/
public function setProjectId($project_id) {
if (!empty($project_id)){
$this->project_id = $project_id;
}
if (empty($this->project_id)){
throw new InvalidArgumentException("Please set project_id");
}
}
/**
* Set default cache name
*
* @param string $cache_name name of cache
* @throws InvalidArgumentException
*/
public function setCacheName($cache_name) {
if (!empty($cache_name)){
$this->cache_name = $cache_name;
}
}
public function getCaches($page = 0){
$url = "projects/{$this->project_id}/caches";
$params = array();
if($page > 0) {
$params['page'] = $page;
}
$this->setJsonHeaders();
return self::json_decode($this->apiCall(self::GET, $url, $params));
}
/**
* Get information about cache.
* Also returns cache size.
*
* @param string $cache
* @return mixed
*/
public function getCache($cache) {
$cache = self::encodeCache($cache);
$url = "projects/{$this->project_id}/caches/$cache";
$this->setJsonHeaders();
return self::json_decode($this->apiCall(self::GET, $url));
}
/**
* Push a item on the cache at 'key'
*
* Examples:
* <code>
* $cache->putItem("test_cache", 'default', "Hello world");
* </code>
* <code>
* $cache->putItem("test_cache", 'default', array(
* "value" => "Test Item",
* 'expires_in' => 2*24*3600, # 2 days
* "replace" => true
* ));
* </code>
*
* @param string $cache Name of the cache.
* @param string $key Item key.
* @param array|string $item
*
* @return mixed
*/
public function putItem($cache, $key, $item) {
$cache = self::encodeCache($cache);
$key = self::encodeKey($key);
$itm = new IronCache_Item($item);
$req = $itm->asArray();
$url = "projects/{$this->project_id}/caches/$cache/items/$key";
$this->setJsonHeaders();
$res = $this->apiCall(self::PUT, $url, $req);
return self::json_decode($res);
}
/**
* Get item from cache by key
*
* @param string $cache Cache name
* @param string $key Cache key
* @return mixed|null single item or null
* @throws Http_Exception
*/
public function getItem($cache, $key) {
$cache = self::encodeCache($cache);
$key = self::encodeKey($key);
$url = "projects/{$this->project_id}/caches/$cache/items/$key";
$this->setJsonHeaders();
try {
$res = $this->apiCall(self::GET, $url);
}catch (Http_Exception $e){
if ($e->getCode() == Http_Exception::NOT_FOUND){
return null;
}else{
throw $e;
}
}
return self::json_decode($res);
}
public function deleteItem($cache, $key) {
$cache = self::encodeCache($cache);
$key = self::encodeKey($key);
$url = "projects/{$this->project_id}/caches/$cache/items/$key";
$this->setJsonHeaders();
return self::json_decode($this->apiCall(self::DELETE, $url));
}
/**
* Atomically increments the value for key by amount.
* Can be used for both increment and decrement by passing a negative value.
* The value must exist and must be an integer.
* The number is treated as an unsigned 64-bit integer.
* The usual overflow rules apply when adding, but subtracting from 0 always yields 0.
*
* @param string $cache
* @param string $key
* @param int $amount Change by this value
* @return mixed|void
*/
public function incrementItem($cache, $key, $amount = 1){
$cache = self::encodeCache($cache);
$key = self::encodeKey($key);
$url = "projects/{$this->project_id}/caches/$cache/items/$key/increment";
$params = array(
'amount' => $amount
);
$this->setJsonHeaders();
return self::json_decode($this->apiCall(self::POST, $url, $params));
}
/**
* Shortcut for getItem($cache, $key)
* Please set $cache name before use by setCacheName() method
*
* @param string $key
* @return mixed|null
* @throws InvalidArgumentException
*/
public function get($key){
return $this->getItem($this->cache_name, $key);
}
/**
* Shortcut for putItem($cache, $key, $item)
* Please set $cache name before use by setCacheName() method
*
* @param string $key
* @param array|string $item
* @return mixed
* @throws InvalidArgumentException
*/
public function put($key, $item){
return $this->putItem($this->cache_name, $key, $item);
}
/**
* Shortcut for deleteItem($cache, $key)
* Please set $cache name before use by setCacheName() method
*
* @param string $key
* @return mixed|void
* @throws InvalidArgumentException
*/
public function delete($key){
return $this->deleteItem($this->cache_name, $key);
}
/**
* Shortcut for incrementItem($cache, $key, $amount)
* Please set $cache name before use by setCacheName() method
*
* @param string $key
* @param int $amount
* @return mixed|void
* @throws InvalidArgumentException
*/
public function increment($key, $amount = 1){
return $this->incrementItem($this->cache_name, $key, $amount);
}
/**
* Clear a Cache
* Delete all items in a cache. This cannot be undone.
*
* @param string|null $cache Cache name or null
* @return mixed
*/
public function clear($cache = null) {
if ($cache === null){
$cache = $this->cache_name;
}
$cache = self::encodeCache($cache);
$url = "projects/{$this->project_id}/caches/$cache/clear";
$params = array();
$this->setJsonHeaders();
return self::json_decode($this->apiCall(self::POST, $url, $params));
}
function session_open($savePath, $sessionName){
$this->setCacheName($sessionName);
return true;
}
function session_close(){
return true;
}
function session_read($id){
$item = $this->get($id);
if ($item !== null) {
return $item->value;
} else {
return null;
}
}
function session_write($id, $data){
$this->put($id, array(
"value" => $data,
"expires_in" => $this->session_expire_time
));
return true;
}
function session_destroy($id){
try {
$this->delete($id);
} catch (Exception $e) {}
return true;
}
function session_gc($maxlifetime){
# auto-expire by default, no need for gc
return true;
}
/**
* Set IronCache as session store handler
*
* @param null|integer $session_expire_time Expire time in seconds
*/
function set_as_session_store($session_expire_time = null){
if ($session_expire_time != null){
$this->session_expire_time = $session_expire_time;
}
session_set_save_handler(
array($this, 'session_open'),
array($this, 'session_close'),
array($this, 'session_read'),
array($this, 'session_write'),
array($this, 'session_destroy'),
array($this, 'session_gc')
);
}
/* PRIVATE FUNCTIONS */
private static function encodeCache($cache){
if (empty($cache)){
throw new InvalidArgumentException('Please set $cache variable');
}
return rawurlencode($cache);
}
private static function encodeKey($key){
if (empty($key)){
throw new InvalidArgumentException('Please set $key variable');
}
return rawurlencode($key);
}
private function setJsonHeaders(){
$this->setCommonHeaders();
}
private function setPostHeaders(){
$this->setCommonHeaders();
$this->headers['Content-Type'] ='multipart/form-data';
}
}