Passed
Push — master ( 4c5faf...429320 )
by Chris
04:23
created

ReCaptcha3Validator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 101
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 101
ccs 0
cts 36
cp 0
rs 10
wmc 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setMinScore() 0 5 1
A getMinScore() 0 3 1
A getAction() 0 3 1
A setAction() 0 5 1
A __construct() 0 4 1
A isValid() 0 17 5
1
<?php
2
3
namespace WebTheory\Saveyour\Validators;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use WebTheory\Saveyour\Contracts\FormValidatorInterface;
7
use WebTheory\Saveyour\Request;
8
9
class ReCaptcha3Validator implements FormValidatorInterface
10
{
11
    /**
12
     *
13
     */
14
    protected $reCaptcha;
15
16
    /**
17
     *
18
     */
19
    protected $secret;
20
21
    /**
22
     * @var string
23
     */
24
    protected $action = '';
25
26
    /**
27
     * @var float
28
     */
29
    protected $minScore = 0.5;
30
31
    public const URL = 'https://www.google.com/recaptcha/api/siteverify';
32
33
    /**
34
     *
35
     */
36
    public function __construct(string $reCaptcha, string $secret)
37
    {
38
        $this->reCaptcha = $reCaptcha;
39
        $this->secret = $secret;
40
    }
41
42
    /**
43
     * Get the value of action
44
     *
45
     * @return string
46
     */
47
    public function getAction(): string
48
    {
49
        return $this->action;
50
    }
51
52
    /**
53
     * Set the value of action
54
     *
55
     * @param string $action
56
     *
57
     * @return self
58
     */
59
    public function setAction(string $action)
60
    {
61
        $this->action = $action;
62
63
        return $this;
64
    }
65
66
    /**
67
     * Get the value of minScore
68
     *
69
     * @return float
70
     */
71
    public function getMinScore(): float
72
    {
73
        return $this->minScore;
74
    }
75
76
    /**
77
     * Set the value of minScore
78
     *
79
     * @param float $minScore
80
     *
81
     * @return self
82
     */
83
    public function setMinScore(float $minScore)
84
    {
85
        $this->minScore = $minScore;
86
87
        return $this;
88
    }
89
90
    /**
91
     *
92
     */
93
    public function isValid(ServerRequestInterface $request): bool
94
    {
95
        $response = Request::var($request, $this->reCaptcha);
96
97
        $url = static::URL . "?secret={$this->secret}&response={$response}";
98
99
        $status = json_decode(file_get_contents($url), true);
100
101
        if (
102
            true === $status['success']
103
            && $status['score'] >= $this->minScore
104
            && ($status['action'] == $this->action || empty($this->action))
105
        ) {
106
            return true;
107
        }
108
109
        return false;
110
    }
111
}
112