Alert   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 21
c 2
b 0
f 0
dl 0
loc 44
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A boot() 0 2 1
A output() 0 22 4
A getOutputContent() 0 13 2
1
<?php
2
3
namespace BeyondCode\QueryDetector\Outputs;
4
5
use Illuminate\Support\Collection;
6
use Symfony\Component\HttpFoundation\Response;
7
8
class Alert implements Output
9
{
10
    public function boot()
11
    {
12
        //
13
    }
14
15
    public function output(Collection $detectedQueries, Response $response)
16
    {
17
        if (stripos($response->headers->get('Content-Type'), 'text/html') !== 0 || $response->isRedirection()) {
18
            return;
19
        }
20
21
        $content = $response->getContent();
22
23
        $outputContent = $this->getOutputContent($detectedQueries);
24
25
        $pos = strripos($content, '</body>');
26
27
        if (false !== $pos) {
28
            $content = substr($content, 0, $pos) . $outputContent . substr($content, $pos);
29
        } else {
30
            $content = $content . $outputContent;
31
        }
32
33
        // Update the new content and reset the content length
34
        $response->setContent($content);
35
36
        $response->headers->remove('Content-Length');
37
    }
38
39
    protected function getOutputContent(Collection $detectedQueries)
40
    {
41
        $output = '<script type="text/javascript">';
42
        $output .= "alert('Found the following N+1 queries in this request:\\n\\n";
43
        foreach ($detectedQueries as $detectedQuery) {
44
            $output .= "Model: ".addslashes($detectedQuery['model'])." => Relation: ".addslashes($detectedQuery['relation']);
45
            $output .= " - You should add \"with(\'".addslashes($detectedQuery['relation'])."\')\" to eager-load this relation.";
46
            $output .= "\\n";
47
        }
48
        $output .= "')";
49
        $output .= '</script>';
50
51
        return $output;
52
    }
53
}
54