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

Recaptcha3Validator::validate()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 9.0197

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 9
eloc 15
c 3
b 0
f 0
nc 6
nop 2
dl 0
loc 24
ccs 15
cts 16
cp 0.9375
crap 9.0197
rs 8.0555
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