Completed
Push — master ( a16228...1270a6 )
by Dmitrii
04:19 queued 01:51
created

Recaptcha3Validator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 95.24%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 22
c 3
b 0
f 0
dl 0
loc 42
ccs 20
cts 21
cp 0.9524
rs 10
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
11
final class Recaptcha3Validator extends ConstraintValidator
12
{
13
    /** @var ReCaptcha */
14
    private $recaptcha;
15
16
    /** @var bool */
17
    private $enabled;
18
19
    /** @var IpResolverInterface */
20
    private $ipResolver;
21
22 9
    public function __construct($recaptcha, bool $enabled, IpResolverInterface $ipResolver)
23
    {
24 9
        $this->recaptcha = $recaptcha;
25 9
        $this->enabled = $enabled;
26 9
        $this->ipResolver = $ipResolver;
27 9
    }
28
29 9
    public function validate($value, Constraint $constraint): void
30
    {
31 9
        if (!$constraint instanceof Recaptcha3) {
32
            throw new UnexpectedTypeException($constraint, Recaptcha3::class);
33
        }
34 9
        if (null === $value || '' === $value) {
35 2
            return;
36
        }
37 7
        if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
38 1
            throw new UnexpectedTypeException($value, 'string');
39
        }
40
41 6
        if (!$this->enabled) {
42 2
            return;
43
        }
44
45 4
        $ip = $this->ipResolver->resolveIp();
46
47 4
        $response = $this->recaptcha->verify($value, $ip);
48 4
        if (!$response->isSuccess()) {
49 2
            $this->context->buildViolation($constraint->message)
50 2
                ->setParameter('{{ value }}', $this->formatValue($value))
51 2
                ->setCode(Recaptcha3::INVALID_FORMAT_ERROR)
52 2
                ->addViolation();
53
        }
54 4
    }
55
}
56