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

TokenValidator::validateAttribute()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6.0493

Importance

Changes 5
Bugs 0 Features 1
Metric Value
cc 6
eloc 13
c 5
b 0
f 1
nc 12
nop 2
dl 0
loc 18
ccs 8
cts 9
cp 0.8889
crap 6.0493
rs 9.2222
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