|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Library for confirmation tokens. |
|
4
|
|
|
* |
|
5
|
|
|
* @link https://github.com/hiqdev/php-confirmator |
|
6
|
|
|
* @package php-confirmator |
|
7
|
|
|
* @license BSD-3-Clause |
|
8
|
|
|
* @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/) |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace hiqdev\php\confirmator; |
|
12
|
|
|
|
|
13
|
|
|
trait ServiceTrait |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @param array $data |
|
17
|
|
|
* @return Token |
|
18
|
|
|
*/ |
|
19
|
3 |
|
public function issueToken(array $data) |
|
20
|
|
|
{ |
|
21
|
3 |
|
$token = new Token($this, $data); |
|
22
|
3 |
|
$this->writeToken($token); |
|
23
|
|
|
|
|
24
|
3 |
|
return $token; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
1 |
|
public function checkToken($token, array $data) |
|
28
|
|
|
{ |
|
29
|
1 |
|
$token = $this->findToken($token); |
|
30
|
1 |
|
if (!$token) { |
|
31
|
|
|
return false; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
1 |
|
return $token->check($data); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function checkData(array $data) |
|
38
|
|
|
{ |
|
39
|
|
|
$token = $this->findToken($data['token'] ?? null); |
|
40
|
|
|
if (!$token) { |
|
41
|
|
|
return []; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
unset($data['token']); |
|
45
|
|
|
|
|
46
|
|
|
return $token->check($data) ? $token->mget() : []; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
2 |
|
public function findToken($token) |
|
50
|
|
|
{ |
|
51
|
2 |
|
if ($token instanceof Token) { |
|
52
|
1 |
|
return $token; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
2 |
|
$data = $this->readToken($token); |
|
56
|
|
|
|
|
57
|
2 |
|
return empty($data) ? null : new Token($this, $data, $token); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function removeToken($token) |
|
61
|
|
|
{ |
|
62
|
|
|
return $this->getStorage()->remove((string) $token); |
|
|
|
|
|
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
2 |
|
protected function readToken($string) |
|
66
|
|
|
{ |
|
67
|
2 |
|
return $this->getStorage()->has($string) ? json_decode($this->getStorage()->get($string), true) : null; |
|
|
|
|
|
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
3 |
|
protected function writeToken(Token $token) |
|
71
|
|
|
{ |
|
72
|
3 |
|
return $this->getStorage()->set((string) $token, json_encode($token->mget())); |
|
|
|
|
|
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.