Test Failed
Push — master ( c65274...a98fd4 )
by Alexander
18:33
created

TokenValidator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 5
Bugs 0 Features 1
Metric Value
eloc 24
c 5
b 0
f 1
dl 0
loc 50
ccs 11
cts 12
cp 0.9167
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validateAttribute() 0 18 6
A __construct() 0 7 3
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