1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Wearesho\Yii\Validators; |
6
|
|
|
|
7
|
|
|
use Wearesho\Yii\Exceptions\DeliveryLimitReachedException; |
8
|
|
|
use Wearesho\Yii\Interfaces\TokenableEntityInterface; |
9
|
|
|
use Wearesho\Yii\Interfaces\TokenRepositoryInterface; |
10
|
|
|
|
11
|
|
|
use yii\base\InvalidConfigException; |
12
|
|
|
use yii\base\Model; |
13
|
|
|
use yii\validators\Validator; |
14
|
|
|
|
15
|
|
|
class TokenValidator extends Validator |
16
|
|
|
{ |
17
|
|
|
public ?string $recipientAttribute = null; |
18
|
|
|
|
19
|
|
|
public TokenableEntityInterface|\Closure|null $recipient = null; |
20
|
|
|
|
21
|
|
|
public ?string $targetAttribute = null; |
22
|
|
|
|
23
|
|
|
public $message = null; |
24
|
|
|
|
25
|
|
|
public ?string $limitReachedMessage = null; |
26
|
|
|
|
27
|
|
|
protected TokenRepositoryInterface $repository; |
28
|
|
|
|
29
|
|
|
public function __construct(TokenRepositoryInterface $repository, array $config = []) |
30
|
|
|
{ |
31
|
|
|
parent::__construct($config); |
32
|
|
|
|
33
|
|
|
$this->repository = $repository; |
34
|
|
|
$this->message = $this->message ?: \Yii::t('yii', '{attribute} is invalid.'); |
35
|
|
|
$this->limitReachedMessage = $this->limitReachedMessage ?: \Yii::t('yii', 'Limit of messages is reached'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param Model $model |
40
|
5 |
|
* @param string $attribute |
41
|
|
|
*/ |
42
|
5 |
|
public function validateAttribute($model, $attribute) |
43
|
|
|
{ |
44
|
5 |
|
$recipient = is_callable($this->recipient) |
45
|
5 |
|
? call_user_func($this->recipient, $model, $attribute) |
|
|
|
|
46
|
5 |
|
: $model->{$this->recipientAttribute}; |
47
|
5 |
|
|
48
|
|
|
if (!$recipient instanceof TokenableEntityInterface) { |
49
|
|
|
throw new InvalidConfigException( |
50
|
|
|
"recipient attribute have to be either TokenableEntityInterface " |
51
|
|
|
. "or Closure with return type of TokenableEntityInterface" |
52
|
|
|
); |
53
|
4 |
|
} |
54
|
|
|
|
55
|
4 |
|
$token = $model->{$attribute}; |
56
|
|
|
|
57
|
4 |
|
try { |
58
|
|
|
$token = $this->repository->verify($recipient, $token); |
59
|
4 |
|
if (!empty($this->targetAttribute) && $model->canSetProperty($this->targetAttribute)) { |
60
|
|
|
$model->{$this->targetAttribute} = $token; |
61
|
|
|
} |
62
|
4 |
|
} catch (DeliveryLimitReachedException $ex) { |
63
|
1 |
|
$this->addError($model, $attribute, $this->limitReachedMessage); |
64
|
1 |
|
} catch (\Throwable $ex) { |
65
|
|
|
$this->addError($model, $attribute, $this->message, [ |
|
|
|
|
66
|
3 |
|
'attribute' => $attribute, |
67
|
|
|
]); |
68
|
3 |
|
} |
69
|
3 |
|
} |
70
|
|
|
} |
71
|
|
|
|