Passed
Push — master ( 8f669d...12a285 )
by Dmitrii
01:40 queued 10s
created

Recaptcha3Validator::validate()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 9.0608

Importance

Changes 0
Metric Value
cc 9
eloc 15
nc 6
nop 2
dl 0
loc 24
ccs 10
cts 11
cp 0.9091
crap 9.0608
rs 8.0555
c 0
b 0
f 0
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