1 | <?php |
||
13 | class Token |
||
14 | { |
||
15 | protected $service; |
||
16 | |||
17 | protected $data = []; |
||
18 | |||
19 | protected $string; |
||
20 | |||
21 | public function __construct(ServiceInterface $service, array $data = [], $string = null) |
||
22 | { |
||
23 | $this->service = $service; |
||
24 | $this->data = $this->prepareData($data); |
||
25 | $this->string = $string ?: $this->genString(); |
||
26 | } |
||
27 | |||
28 | protected function prepareData(array $data) |
||
29 | { |
||
30 | if (empty($data['notAfter'])) { |
||
31 | $data['notAfter'] = '+ 1 week'; |
||
32 | } |
||
33 | foreach ($data as $key => &$value) { |
||
34 | if ($key === 'notAfter' || $key === 'notBefore') { |
||
35 | $value = date('Y-m-d H:i:s', strtotime($value)); |
||
36 | } |
||
37 | } |
||
38 | |||
39 | return $data; |
||
40 | } |
||
41 | |||
42 | public function __toString() |
||
43 | { |
||
44 | return $this->string; |
||
45 | } |
||
46 | |||
47 | public function genString($length = 32) |
||
48 | { |
||
49 | $res = ''; |
||
50 | $chars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
||
51 | $last = strlen($chars) - 1; |
||
52 | for ($i = 0; $i < $length; ++$i) { |
||
53 | $res .= $chars[mt_rand(0, $last)]; |
||
54 | } |
||
55 | |||
56 | return $res; |
||
57 | } |
||
58 | |||
59 | public function get($key, $default = null) |
||
60 | { |
||
61 | return isset($this->data[$key]) ? $this->data[$key] : $default; |
||
62 | } |
||
63 | |||
64 | public function mget() |
||
65 | { |
||
66 | return $this->data; |
||
67 | } |
||
68 | |||
69 | public function remove() |
||
73 | |||
74 | public function check(array $data) |
||
75 | { |
||
76 | return $this->checkNotAfter() && $this->checkNotBefore() && $this->checkData($data); |
||
77 | } |
||
78 | |||
79 | public function checkData(array $data) |
||
80 | { |
||
89 | |||
90 | public function checkNotBefore() |
||
98 | |||
99 | public function checkNotAfter() |
||
107 | } |
||
108 |