LaravelCaffeineDripMiddleware   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 12
Bugs 1 Features 1
Metric Value
wmc 8
eloc 29
c 12
b 1
f 1
dl 0
loc 54
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A makeRegex() 0 3 1
B handle() 0 47 7
1
<?php namespace GeneaLabs\LaravelCaffeine\Http\Middleware;
2
3
use Closure;
4
use GeneaLabs\LaravelCaffeine\Dripper;
5
use Illuminate\Http\Request;
6
7
class LaravelCaffeineDripMiddleware
8
{
9
    public function handle(Request $request, Closure $next)
10
    {
11
        $response = $next($request);
12
13
        $content = $response->getContent();
14
15
        if (! is_string($content) || strlen(trim($content)) === 0) {
16
            return $response;
17
        }
18
19
        $shouldDripRegexp = $this->makeRegex([
20
            '<meta\s+',
21
            '(name\s*=\s*[\'"]caffeinated[\'"]\s+content\s*=\s*[\'"]false[\'"]',
22
            '|content\s*=\s*[\'"]false[\'"]\s+name\s*=\s*[\'"]caffeinated[\'"])',
23
        ]);
24
25
        $shouldNotDrip = preg_match($shouldDripRegexp, $content);
26
27
        if ($shouldNotDrip) {
28
            return $response;
29
        }
30
31
        $formTokenRegexp = $this->makeRegex([
32
            "<input.*?name\s*=\s*[\'\"]_token[\'\"]",
33
        ]);
34
        $metaTokenRegexp = $this->makeRegex([
35
            "<meta.*?name\s*=\s*[\'\"]csrf[_-]token[\'\"]",
36
        ]);
37
        $hasNoFormToken = ! preg_match($formTokenRegexp, $content);
38
        $hasNoMetaToken = ! preg_match($metaTokenRegexp, $content);
39
40
        if ($hasNoFormToken && $hasNoMetaToken) {
41
            return $response;
42
        }
43
44
        $dripper = (new Dripper);
45
        $content = preg_replace('/(<\/html>)\s*\z/', $dripper->html . "</html>", $content);
46
47
        if (! preg_match_all('/(<\/html>)\s*\z/', $content, $matches)) {
48
            $content .= $dripper->html;
49
        }
50
51
        $original = $response->original;
52
        $response->setContent($content);
53
        $response->original = $original;
54
55
        return $response;
56
    }
57
58
    protected function makeRegex(array $regexp) : string
59
    {
60
        return '/' . implode('', $regexp) . '/';
61
    }
62
}
63