ReCaptchaTrueValidator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 21
c 1
b 0
f 0
dl 0
loc 75
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A validate() 0 21 5
1
<?php
2
3
namespace App\Validator\Constraints;
4
5
use ReCaptcha\ReCaptcha;
6
use Symfony\Component\HttpFoundation\RequestStack;
7
use Symfony\Component\Validator\Constraint;
8
use Symfony\Component\Validator\ConstraintValidator;
9
10
class ReCaptchaTrueValidator extends ConstraintValidator
11
{
12
    /**
13
     * Enable recaptcha?
14
     *
15
     * @var bool
16
     */
17
    protected $enabled;
18
19
    /**
20
     * Recaptcha Private Key.
21
     *
22
     * @var string
23
     */
24
    protected $privateKey;
25
26
    /**
27
     * Request Stack.
28
     *
29
     * @var RequestStack
30
     */
31
    protected $requestStack;
32
33
    /**
34
     * HTTP Proxy information.
35
     *
36
     * @var array
37
     */
38
    protected $httpProxy;
39
40
    /**
41
     * Enable server side host check.
42
     *
43
     * @var bool
44
     */
45
    protected $verifyHost;
46
47
    /**
48
     * @param bool         $enabled      Whether ReCaptcha is enabled
49
     * @param string       $privateKey   The private key
50
     * @param RequestStack $requestStack The request stack
51
     * @param bool         $verifyHost   Whether to verify the host
52
     */
53
    public function __construct($enabled, $privateKey, RequestStack $requestStack, $verifyHost)
54
    {
55
        $this->enabled = $enabled;
56
        $this->privateKey = $privateKey;
57
        $this->requestStack = $requestStack;
58
        $this->verifyHost = $verifyHost;
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function validate($value, Constraint $constraint)
65
    {
66
        // if recaptcha is disabled, always valid
67
        if (!$this->enabled) {
68
            return;
69
        }
70
71
        // define variable for recaptcha check answer
72
        $masterRequest = $this->requestStack->getMasterRequest();
73
        $remoteip = $masterRequest->getClientIp();
74
        $answer = $masterRequest->get('g-recaptcha-response');
75
76
        // Verify user response with Google
77
        $recaptcha = new ReCaptcha($this->privateKey);
78
        $response = $recaptcha->verify($answer, $remoteip);
79
80
        if (!$response->isSuccess()) {
81
            $this->context->addViolation($constraint->message);
82
        } elseif ($this->verifyHost && $response['hostname'] !== $masterRequest->getHost()) {
83
            // Perform server side hostname check
84
            $this->context->addViolation($constraint->invalidHostMessage);
85
        }
86
    }
87
}
88