Passed
Push — master ( 815bbe...b873e2 )
by Pavel
06:06 queued 02:40
created

HtmlMinify::handle()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 3
b 0
f 0
nc 5
nop 2
dl 0
loc 21
rs 9.9332
1
<?php
2
3
namespace Abordage\LaravelHtmlMin\Middleware;
4
5
use Abordage\LaravelHtmlMin\Facades\HtmlMin;
6
use Closure;
7
use Illuminate\Http\Request;
8
use Illuminate\Http\Response;
9
10
class HtmlMinify
11
{
12
    /**
13
     * @param Request $request
14
     * @param Closure $next
15
     * @return Response|mixed
16
     */
17
    public function handle(Request $request, Closure $next)
18
    {
19
        $response = $next($request);
20
21
        if (!$this->compressionPossible($request, $response)) {
22
            return $response;
23
        }
24
25
        $html = $response->getContent();
26
27
        if (class_exists('\BeyondCode\ServerTiming\Facades\ServerTiming')) {
28
            \BeyondCode\ServerTiming\Facades\ServerTiming::start('Minification');
29
        }
30
31
        $htmlMin = HtmlMin::minify($html);
32
33
        if (class_exists('\BeyondCode\ServerTiming\Facades\ServerTiming')) {
34
            \BeyondCode\ServerTiming\Facades\ServerTiming::stop('Minification');
35
        }
36
37
        return $response->setContent($htmlMin);
38
    }
39
40
    /**
41
     * @param Request $request
42
     * @param mixed $response
43
     * @return bool
44
     */
45
    private function compressionPossible(Request $request, $response): bool
46
    {
47
        if (!config('html-min.enable')) {
48
            return false;
49
        }
50
51
        if (!in_array(strtoupper($request->getMethod()), ['GET', 'HEAD'])) {
52
            return false;
53
        }
54
55
        if (!$response instanceof Response) {
56
            return false;
57
        }
58
59
        if ($response->getStatusCode() >= 500) {
60
            return false;
61
        }
62
63
        return true;
64
    }
65
}
66