1<?php namespace GeneaLabs\LaravelCaffeine\Http\Middleware;
2
3use Closure;
4use GeneaLabs\LaravelCaffeine\Dripper;
5use Illuminate\Http\Request;
6
7class 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