GoogleRecaptchaMiddleware   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 4
dl 0
loc 74
ccs 0
cts 27
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A __invoke() 0 25 4
1
<?php
2
namespace Germania\GoogleRecaptcha;
3
4
use Psr\Log\LoggerInterface;
5
use Psr\Log\LoggerAwareInterface;
6
use Psr\Log\LoggerAwareTrait;
7
use Psr\Log\NullLogger;
8
9
use Psr\Http\Message\ServerRequestInterface as Request;
10
use Psr\Http\Message\ResponseInterface as Response;
11
12
13
class GoogleRecaptchaMiddleware implements LoggerAwareInterface
14
{
15
    use LoggerAwareTrait;
16
17
18
    /**
19
     * @var Callable
20
     */
21
    public $validator;
22
23
    /**
24
     * @var string
25
     */
26
    public $input_field;
27
28
    /**
29
     * @var string
30
     */
31
    public $client_ip;
32
33
    /**
34
     * @var string
35
     */
36
    public $request_attribute;
37
38
    /**
39
     * @var int
40
     */
41
    public $http_status_code;
42
43
    /**
44
     * @var null|bool
45
     */
46
    public $status;
47
48
49
    public function __construct( callable $validator, $client_ip, $input_field, $request_attribute, $http_status_code, LoggerInterface $logger = null )
50
    {
51
        $this->validator   = $validator;
52
        $this->client_ip   = $client_ip;
53
        $this->input_field = $input_field;
54
        $this->request_attribute = $request_attribute;
55
        $this->http_status_code  = $http_status_code;
56
57
        $this->setLogger($logger ?: new NullLogger);
58
    }
59
60
61
    public function __invoke(Request $request, Response $response, $next)
62
    {
63
        $post_data = $request->getParsedBody() ?: array();
64
65
        $recaptcha_validator = $this->validator;
66
67
        if (empty($post_data[ $this->input_field ])
68
        or !$recaptcha_validator( $post_data[ $this->input_field ], $this->client_ip)):
69
            $this->status = false;
70
            $response = $response->withStatus( $this->http_status_code );
71
        else:
72
            $this->status = true;
73
        endif;
74
75
        // Store result in Request
76
        $request = $request->withAttribute( $this->request_attribute, [
77
            'failed'  => !$this->status,
78
            'success' => $this->status,
79
            'status'  => $this->status
80
        ]);
81
82
        // Call $next middleware
83
        return $next($request, $response);
84
85
    }
86
}
87