/
ValueTrait.php
89 lines (77 loc) · 1.94 KB
/
ValueTrait.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
<?php namespace AdammBalogh\KeyValueStore\Adapter\MemoryAdapter;
use AdammBalogh\KeyValueStore\Adapter\Util;
use AdammBalogh\KeyValueStore\Exception\KeyNotFoundException;
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
trait ValueTrait
{
/**
* Gets the value of a key.
*
* @param string $key
*
* @return mixed The value of the key.
*
* @throws KeyNotFoundException
*/
public function get($key)
{
return $this->getValue($key);
}
/**
* Sets the value of a key.
*
* @param string $key
* @param mixed $value Can be any of serializable data type.
*
* @return bool True if the set was successful, false if it was unsuccessful.
*/
public function set($key, $value)
{
$this->store[$key] = $value;
return true;
}
/**
* Gets value, watches expiring.
*
* @param string $key
*
* @return mixed
*
* @throws KeyNotFoundException
*/
protected function getValue($key)
{
if (!array_key_exists($key, $this->store)) {
throw new KeyNotFoundException();
}
$getResult = $this->store[$key];
$unserialized = @unserialize($getResult);
if (Util::hasInternalExpireTime($unserialized)) {
$this->handleTtl($key, $unserialized['ts'], $unserialized['s']);
$getResult = $unserialized['v'];
}
return $getResult;
}
/**
* If ttl is lesser or equals 0 delete key.
*
* @param string $key
* @param int $expireSetTs
* @param int $expireSec
*
* @return int ttl
*
* @throws KeyNotFoundException
*/
protected function handleTtl($key, $expireSetTs, $expireSec)
{
$ttl = $expireSetTs + $expireSec - time();
if ($ttl <= 0) {
unset($this->store[$key]);
throw new KeyNotFoundException();
}
return $ttl;
}
}