Completed
Pull Request — master (#7)
by Lars
01:09
created

ProtectAgainstSpam   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 4
dl 0
loc 46
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B handle() 0 28 7
A respondToSpam() 0 6 1
1
<?php
2
3
namespace Spatie\Honeypot;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
use Symfony\Component\HttpFoundation\Response;
8
use Spatie\Honeypot\SpamResponder\SpamResponder;
9
10
class ProtectAgainstSpam
11
{
12
    /** @var \Spatie\Honeypot\SpamResponder\SpamResponder */
13
    protected $spamResponder;
14
15
    public function __construct(SpamResponder $spamResponder)
16
    {
17
        $this->spamResponder = $spamResponder;
18
    }
19
20
    public function handle(Request $request, Closure $next): Response
21
    {
22
        if (! config('honeypot.enabled')) {
23
            return $next($request);
24
        }
25
26
        $honeypotValue = $request->get(config('honeypot.name_field_name'));
27
28
        if (config('honeypot.random_name_field_name')) {
29
            if (! $request->has(session()->get('name_field_name'))) {
30
                return $this->respondToSpam($request, $next);
31
            }
32
33
            $honeypotValue = $request->get(session()->get('name_field_name'));
34
        }
35
36
        if (! empty($honeypotValue)) {
37
            return $this->respondToSpam($request, $next);
38
        }
39
40
        if ($validFrom = $request->get(config('honeypot.valid_from_field_name'))) {
41
            if ((new EncryptedTime($validFrom))->isFuture()) {
42
                return $this->respondToSpam($request, $next);
43
            }
44
        }
45
46
        return $next($request);
47
    }
48
49
    protected function respondToSpam(Request $request, Closure $next): Response
50
    {
51
        event(new SpamDetected($request));
52
53
        return $this->spamResponder->respond($request, $next);
54
    }
55
}
56