ReCaptchaComponent::init()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 10
cp 0
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 12
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\Component;
13
14
use Yii;
15
use yii\base\Component;
16
use yii\base\InvalidConfigException;
17
use yii\httpclient\Client;
18
19
class ReCaptchaComponent extends Component
20
{
21
    /**
22
     * @var string the ReCAPTCHA sitekey
23
     */
24
    public $key;
25
    /**
26
     * @var string the shared key between the site and ReCAPTCHA
27
     */
28
    public $secret;
29
30
    /**
31
     * @inheritdoc
32
     *
33
     * @throws InvalidConfigException
34
     */
35
    public function init()
36
    {
37
        if (empty($this->key)) {
38
            throw new InvalidConfigException(Yii::t('usuario', 'Required "key" cannot be empty.'));
39
        }
40
41
        if (empty($this->secret)) {
42
            throw new InvalidConfigException(Yii::t('usuario', 'Required "secret" cannot be empty.'));
43
        }
44
45
        parent::init();
46
    }
47
48
    /**
49
     * Verifies whether a user response is valid or not.
50
     *
51
     * @param $value
52
     *
53
     * @return bool
54
     */
55
    public function verify($value)
56
    {
57
        $response = (new Client(
58
            [
59
                'baseUrl' => 'https://www.google.com/recaptcha/api',
60
                'responseConfig' => [
61
                    'format' => Client::FORMAT_JSON
62
                ]
63
            ]
64
        ))
65
            ->get(
66
                'siteverify',
67
                [
68
                    'secret' => $this->secret,
69
                    'response' => $value,
70
                    'remoteip' => Yii::$app->request->getUserIP()
71
                ]
72
            )
73
            ->send();
74
75
        return $response->getData()['success'] ? : false;
76
    }
77
}
78