GoogleRecaptchaCallable::__invoke()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 16
cp 0
rs 9.584
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 12
1
<?php
2
namespace Germania\GoogleRecaptcha;
3
4
use Psr\Log\LoggerInterface;
5
use Psr\Log\NullLogger;
6
use Psr\Log\LoggerAwareInterface;
7
use Psr\Log\LoggerAwareTrait;
8
use ReCaptcha\ReCaptcha;
9
10
class GoogleRecaptchaCallable implements LoggerAwareInterface
11
{
12
    use LoggerAwareTrait;
13
14
15
    /**
16
     * @var ReCaptcha
17
     */
18
    public $recaptcha;
19
20
21
    /**
22
     * @param ReCaptcha            $recaptcha
23
     * @param LoggerInterface|null $logger
24
     */
25
    public function __construct( ReCaptcha $recaptcha, LoggerInterface $logger = null )
26
    {
27
        $this->recaptcha = $recaptcha;
28
        $this->setLogger( $logger ?: new NullLogger );
29
    }
30
31
32
    /**
33
     * @param  string $g_recaptcha_response
34
     * @param  string $remote_ip
35
     * @return bool
36
     *
37
     * See also: https://developers.google.com/recaptcha/docs/verify
38
     */
39
    public function __invoke( $g_recaptcha_response, $remote_ip)
40
    {
41
        $response = $this->recaptcha->verify($g_recaptcha_response, $remote_ip);
42
43
44
        if ($response->isSuccess()) :
45
            $this->logger->info( "Validation successful", [
46
                'remote_ip' => $remote_ip
47
            ]);
48
            return true;
49
        endif;
50
51
52
        $errors = $response->getErrorCodes() ?: array();
53
        $this->logger->notice( "Failed validation", [
54
            'remote_ip' => $remote_ip,
55
            'errors'    => join(",", $errors )
56
        ]);
57
58
        return false;
59
    }
60
}
61