Completed
Pull Request — master (#75)
by Mike
05:24
created

LaravelCaffeineDripMiddleware::handle()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 45
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 8.439
c 0
b 0
f 0
cc 5
eloc 27
nc 4
nop 2
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)) {
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) {
1 ignored issue
show
Bug Best Practice introduced by
The expression $shouldNotDrip of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
28
            return $response;
29
        }
30
31
        $formTokenRegexp = $this->makeRegex([
32
            '<input([^>]*?[\n]?)*[^>]*?name\s*=\s*[\'"]_token[\'"]',
33
        ]);
34
        $metaTokenRegexp = $this->makeRegex([
35
            '<meta\s+',
36
            'name\s*=\s*[\'"]csrf[_-]token[\'"]',
37
        ]);
38
        $hasNoFormToken = ! preg_match($formTokenRegexp, $content);
39
        $hasNoMetaToken = ! preg_match($metaTokenRegexp, $content);
40
41
        if ($hasNoFormToken && $hasNoMetaToken) {
42
            return $response;
43
        }
44
45
        $dripper = (new Dripper);
46
        $content = str_replace(
47
            '</body>',
48
            "{$dripper->html}</body>",
1 ignored issue
show
Bug Best Practice introduced by
The property html does not exist on GeneaLabs\LaravelCaffeine\Dripper. Since you implemented __get, consider adding a @property annotation.
Loading history...
49
            $content
50
        );
51
        $response->setContent($content);
52
53
        return $response;
54
    }
55
56
    protected function makeRegex(array $regexp) : string
57
    {
58
        return '/' . implode('', $regexp) . '/';
59
    }
60
}
61