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

ProtectAgainstSpam::respondToSpam()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
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
        $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