SecurityCaptchaVerifier   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 18.18%

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 33
ccs 2
cts 11
cp 0.1818
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A verifyReCaptcha() 0 13 3
1
<?php
2
3
namespace App\Module\Security\Captcha\Service;
4
5
use App\Infrastructure\Settings\Settings;
6
use App\Module\Security\Enum\SecurityType;
7
use App\Module\Security\Exception\SecurityException;
8
9
class SecurityCaptchaVerifier
10
{
11
    private array $googleSettings;
12
13 42
    public function __construct(
14
        Settings $settings,
15
    ) {
16 42
        $this->googleSettings = $settings->get('google');
17
    }
18
19
    /**
20
     * Ask google API if reCAPTCHA user response is correct or not.
21
     *
22
     * @param string $reCaptchaResponse
23
     * @param SecurityType $exceptionType Exception type (email, login, global)
24
     *
25
     * @throws SecurityException
26
     *
27
     * @return bool true when correct otherwise SecurityException
28
     */
29
    public function verifyReCaptcha(string $reCaptchaResponse, SecurityType $exceptionType): bool
30
    {
31
        $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
32
            urlencode($this->googleSettings['recaptcha']) . '&response=' . urlencode($reCaptchaResponse);
33
        $verificationResponse = file_get_contents($url);
34
        if (
35
            $verificationResponse !== false
36
            && json_decode($verificationResponse, true, 512, JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR)['success']
37
        ) {
38
            return true;
39
        }
40
        $errMsg = 'reCAPTCHA verification failed';
41
        throw new SecurityException('captcha', $exceptionType, $errMsg);
42
    }
43
}
44