Passed
Pull Request — master (#3)
by Dmitrii
03:28
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
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 3
    public function __construct($recaptcha, bool $enabled, IpResolverInterface $ipResolver)
23
    {
24 3
        $this->recaptcha = $recaptcha;
25 3
        $this->enabled = $enabled;
26 3
        $this->ipResolver = $ipResolver;
27 3
    }
28
29 3
    public function validate($value, Constraint $constraint): void
30
    {
31 3
        if (!$constraint instanceof Recaptcha3) {
32
            throw new UnexpectedTypeException($constraint, Recaptcha3::class);
33
        }
34
        if (null === $value || '' === $value) {
35 3
            return;
36 1
        }
37
        if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
38
            throw new UnexpectedTypeException($value, 'string');
39 2
        }
40 2
41
        if (!$this->enabled) {
42 2
            return;
43 2
        }
44 1
45
        $ip = $this->ipResolver->resolveIp();
46 2
47
        $response = $this->recaptcha->verify($value, $ip);
48
        if (!$response->isSuccess()) {
49
            $this->context->buildViolation($constraint->message)
50
                ->setParameter('{{ value }}', $this->formatValue($value))
51
                ->setCode(Recaptcha3::INVALID_FORMAT_ERROR)
52
                ->addViolation();
53
        }
54
    }
55
}
56