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\TokenRepositoryInterface; |
9
|
|
|
|
10
|
|
|
use yii\base\Model; |
11
|
|
|
use yii\validators\Validator; |
12
|
|
|
|
13
|
|
|
class TokenValidator extends Validator |
14
|
|
|
{ |
15
|
|
|
/** @var string */ |
16
|
|
|
public $recipientAttribute; |
17
|
|
|
|
18
|
|
|
/** @var callable */ |
19
|
|
|
public $recipient; |
20
|
|
|
|
21
|
|
|
/** @var string */ |
22
|
|
|
public $targetAttribute; |
23
|
|
|
|
24
|
|
|
/** @var string */ |
25
|
|
|
public $message; |
26
|
|
|
|
27
|
|
|
/** @var string */ |
28
|
|
|
public $limitReachedMessage; |
29
|
|
|
|
30
|
|
|
protected TokenRepositoryInterface $repository; |
31
|
|
|
|
32
|
|
|
public function __construct(TokenRepositoryInterface $repository, array $config = []) |
33
|
|
|
{ |
34
|
|
|
parent::__construct($config); |
35
|
|
|
|
36
|
|
|
$this->repository = $repository; |
37
|
|
|
$this->message = $this->message ?: \Yii::t('yii', '{attribute} is invalid.'); |
38
|
|
|
$this->limitReachedMessage = $this->limitReachedMessage ?: \Yii::t('yii', 'Limit of messages is reached'); |
39
|
|
|
} |
40
|
5 |
|
|
41
|
|
|
/** |
42
|
5 |
|
* @param Model $model |
43
|
|
|
* @param string $attribute |
44
|
5 |
|
*/ |
45
|
5 |
|
public function validateAttribute($model, $attribute) |
46
|
5 |
|
{ |
47
|
5 |
|
$recipient = is_callable($this->recipient) |
48
|
|
|
? call_user_func($this->recipient, $model, $attribute) |
49
|
|
|
: $model->{$this->recipientAttribute}; |
50
|
|
|
|
51
|
|
|
$token = $model->{$attribute}; |
52
|
|
|
|
53
|
4 |
|
try { |
54
|
|
|
$token = $this->repository->verify($recipient, $token); |
55
|
4 |
|
if (!empty($this->targetAttribute) && $model->canSetProperty($this->targetAttribute)) { |
56
|
|
|
$model->{$this->targetAttribute} = $token; |
57
|
4 |
|
} |
58
|
|
|
} catch (DeliveryLimitReachedException $ex) { |
59
|
4 |
|
$this->addError($model, $attribute, $this->limitReachedMessage); |
60
|
|
|
} catch (\Throwable $ex) { |
61
|
|
|
$this->addError($model, $attribute, $this->message, [ |
62
|
4 |
|
'attribute' => $attribute, |
63
|
1 |
|
]); |
64
|
1 |
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|