Completed
Push — master ( ac413c...7a7a6d )
by Freek
02:21 queued 01:13
created

ProtectAgainstSpam::handle()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.4906
c 0
b 0
f 0
cc 7
nc 11
nop 2
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
        $randomizeNameFieldName = config('honeypot.randomize_name_field_name');
27
        $nameFieldName = config('honeypot.name_field_name');
28
29
        if ($randomizeNameFieldName) {
30
            $nameFieldName = $this->getRandomizedNameFieldName($nameFieldName, $request->all());
31
        }
32
33
        $honeypotValue = $request->get($nameFieldName);
34
35
        if (is_null($nameFieldName)) {
36
            return $this->respondToSpam($request, $next);
37
        }
38
39
        if (! empty($honeypotValue)) {
40
            return $this->respondToSpam($request, $next);
41
        }
42
43
        if ($validFrom = $request->get(config('honeypot.valid_from_field_name'))) {
44
            if ((new EncryptedTime($validFrom))->isFuture()) {
45
                return $this->respondToSpam($request, $next);
46
            }
47
        }
48
49
        return $next($request);
50
    }
51
52
    private function getRandomizedNameFieldName($nameFieldName, $requestFields):?String
53
    {
54
        return collect($requestFields)->filter(function ($value, $key) use ($nameFieldName) {
55
            return starts_with($key, $nameFieldName);
56
        })->keys()->first();
57
    }
58
59
    protected function respondToSpam(Request $request, Closure $next): Response
60
    {
61
        event(new SpamDetected($request));
62
63
        return $this->spamResponder->respond($request, $next);
64
    }
65
}
66