Passed
Pull Request — master (#3)
by Dmitrii
03:37
created

Recaptcha3Validator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 42
ccs 15
cts 16
cp 0.9375
rs 10
c 0
b 0
f 0
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B validate() 0 24 9
1
<?php declare(strict_types=1);
2
3
namespace Karser\Recaptcha3Bundle\Validator\Constraints;
4
5
use Karser\Recaptcha3Bundle\Services\IpResolverInterface;
6
use ReCaptcha\ReCaptcha;
7
use Symfony\Component\Validator\Constraint;
8
use Symfony\Component\Validator\ConstraintValidator;
9
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
10
use Symfony\Component\Validator\Exception\UnexpectedValueException;
11
12
final class Recaptcha3Validator extends ConstraintValidator
13
{
14
    /** @var ReCaptcha */
15
    private $recaptcha;
16
17
    /** @var bool */
18
    private $enabled;
19
20
    /** @var IpResolverInterface */
21
    private $ipResolver;
22 3
23
    public function __construct($recaptcha, bool $enabled, IpResolverInterface $ipResolver)
24 3
    {
25 3
        $this->recaptcha = $recaptcha;
26 3
        $this->enabled = $enabled;
27 3
        $this->ipResolver = $ipResolver;
28
    }
29 3
30
    public function validate($value, Constraint $constraint): void
31 3
    {
32
        if (!$constraint instanceof Recaptcha3) {
33
            throw new UnexpectedTypeException($constraint, Recaptcha3::class);
34
        }
35 3
        if (null === $value || '' === $value) {
36 1
            return;
37
        }
38
        if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
39 2
            throw new UnexpectedValueException($value, 'string');
40 2
        }
41
42 2
        if (!$this->enabled) {
43 2
            return;
44 1
        }
45
46 2
        $ip = $this->ipResolver->resolveIp();
47
48
        $response = $this->recaptcha->verify($value, $ip);
49
        if (!$response->isSuccess()) {
50
            $this->context->buildViolation($constraint->message)
51
                ->setParameter('{{ value }}', $this->formatValue($value))
52
                ->setCode(Recaptcha3::INVALID_FORMAT_ERROR)
53
                ->addViolation();
54
        }
55
    }
56
}
57