Passed
Push — master ( 264b27...87ebb2 )
by Dmitrii
03:44
created

Recaptcha3Validator::validateCaptcha()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
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 ($value !== null && !is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
32
            throw new UnexpectedTypeException($value, 'string');
33
        }
34 9
        if (!$constraint instanceof Recaptcha3) {
35 2
            throw new UnexpectedTypeException($constraint, Recaptcha3::class);
36
        }
37 7
        if (!$this->enabled) {
38 1
            return;
39
        }
40
        $value = null !== $value ? (string) $value : '';
41 6
        if (!$this->validateCaptcha($value)) {
42 2
            $this->context->buildViolation($constraint->message)
43
                ->setParameter('{{ value }}', $this->formatValue($value))
44
                ->setCode(Recaptcha3::INVALID_FORMAT_ERROR)
45 4
                ->addViolation();
46
        }
47 4
    }
48 4
49 2
    private function validateCaptcha(string $value): bool
50 2
    {
51 2
        if ($value === '') {
52 2
            return false;
53
        }
54 4
        $ip = $this->ipResolver->resolveIp();
55
        $response = $this->recaptcha->verify($value, $ip);
56
57
        return $response->isSuccess();
58
    }
59
}
60