-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathMemoryCollection.php
More file actions
executable file
·134 lines (116 loc) · 2.46 KB
/
Copy pathMemoryCollection.php
File metadata and controls
executable file
·134 lines (116 loc) · 2.46 KB
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
<?php
namespace Live\Collection;
/**
* Memory collection
*
* @package Live\Collection
*/
class MemoryCollection implements CollectionInterface
{
/**
* Default file expires
*
* @var int Default in seconds
*/
const EXPIRES = 60;
/**
* Collection data
*
* @var array
*/
protected $data;
/**
* Expires in seconds
*
* @var string
*/
protected $expires = self::EXPIRES;
/**
* Constructor
*/
public function __construct()
{
$this->data = [];
}
/**
* {@inheritDoc}
*/
public function get(string $index, $defaultValue = null)
{
if (!$this->has($index)) {
return $defaultValue;
}
return $this->data[$index]['value'];
}
/**
* {@inheritDoc}
*/
public function set(string $index, $value, int $expires = null)
{
if (empty($index) || empty($value)) {
return ;
}
$this->setExpires($expires);
$this->data[$index]['value'] = $value;
$this->data[$index]['expires'] = $this->getExpires();
}
/**
* {@inheritDoc}
*/
public function has(string $index)
{
if (!array_key_exists($index, $this->data)) {
return false;
}
$data = $this->data[$index];
$dateExpires = new \DateTime();
$dateExpires->setTimestamp($data['expires']);
$dateNow = new \DateTime();
return $dateExpires >= $dateNow;
}
/**
* {@inheritDoc}
*/
public function count(): int
{
return count($this->data);
}
/**
* {@inheritDoc}
*/
public function clean()
{
$this->data = [];
}
/**
* Set expiration
*
* @param int $seconds
* @return void
*/
protected function setExpires(int $seconds = null)
{
if (!is_null($seconds) && $seconds > 0) {
$this->expires = $seconds;
} else {
$this->expires = self::EXPIRES;
}
}
/**
* Get expires
*
* @return int timestamp
* @throws \Exception
*/
protected function getExpires(): int
{
try {
$date = new \DateTime();
$date->add(new \DateInterval('PT' . $this->expires . 'S'));
return $date->getTimestamp();
} catch (\Exception $ex) {
$date = new \DateTime();
return $date->getTimestamp();
}
}
}