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

ProtectAgainstSpam   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B handle() 0 34 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
        $nameFieldName = config('honeypot.name_field_name');
27
        $randomNameFieldName = config('honeypot.randomize_name_field_name');
28
        $honeypotValue = $request->get($nameFieldName);
29
30
        if ($randomNameFieldName) {
31
            $nameFieldName = collect($request->all())->filter(function ($value, $key) use ($nameFieldName) {
32
                return preg_match(sprintf('/'.$nameFieldName.'/'), $key);
33
            })->keys()->first();
34
35
            if (is_null($nameFieldName)) {
36
                return $this->respondToSpam($request, $next);
37
            }
38
39
            $honeypotValue = $request->get($nameFieldName);
40
        }
41
42
        if (! empty($honeypotValue)) {
43
            return $this->respondToSpam($request, $next);
44
        }
45
46
        if ($validFrom = $request->get(config('honeypot.valid_from_field_name'))) {
47
            if ((new EncryptedTime($validFrom))->isFuture()) {
48
                return $this->respondToSpam($request, $next);
49
            }
50
        }
51
52
        return $next($request);
53
    }
54
55
    protected function respondToSpam(Request $request, Closure $next): Response
56
    {
57
        event(new SpamDetected($request));
58
59
        return $this->spamResponder->respond($request, $next);
60
    }
61
}
62