ReCaptchaValidator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 2
cbo 3
dl 0
loc 53
ccs 0
cts 24
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 8 2
A clientValidateAttribute() 0 8 2
A validateValue() 0 12 4
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Validator;
13
14
use Da\User\Component\ReCaptchaComponent;
15
use Yii;
16
use yii\base\InvalidConfigException;
17
use yii\validators\Validator;
18
19
class ReCaptchaValidator extends Validator
20
{
21
    /**
22
     * @inheritdoc
23
     */
24
    public $skipOnEmpty = false;
25
    /**
26
     * @var string the message for client validation
27
     */
28
    public $notCheckedMessage;
29
30
    /**
31
     * @inheritdoc
32
     */
33
    public function init()
34
    {
35
        parent::init();
36
37
        if (null === $this->message) {
38
            $this->message = Yii::t('usuario', 'The verification code is incorrect.');
39
        }
40
    }
41
42
    /**
43
     * @inheritdoc
44
     */
45
    public function clientValidateAttribute($model, $attribute, $view)
46
    {
47
        $message = addslashes(
48
            $this->notCheckedMessage ?: Yii::t('usuario', '{0} cannot be blank.', $model->getAttributeLabel($attribute))
49
        );
50
51
        return "(function(messages){if(!grecaptcha.getResponse()){messages.push('{$message}');}})(messages);";
52
    }
53
54
    /**
55
     * @inheritdoc
56
     *
57
     * @throws InvalidConfigException
58
     */
59
    protected function validateValue($value)
60
    {
61
        if (empty($value)) {
62
            if (!($value = Yii::$app->request->post('g-recaptcha-response'))) {
63
                return [$this->message, []];
64
            }
65
        }
66
        /** @var ReCaptchaComponent $recaptcha */
67
        $recaptcha = Yii::$app->get('recaptcha');
68
69
        return $recaptcha->verify($value) ? null : [$this->message, []];
70
    }
71
}
72