Console::output()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 22
rs 9.9
cc 4
nc 3
nop 2
1
<?php
2
3
namespace BeyondCode\QueryDetector\Outputs;
4
5
use Illuminate\Support\Collection;
6
use Symfony\Component\HttpFoundation\Response;
7
8
class Console 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 .= "console.warn('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\\n";
47
            $output .= "Model: ".addslashes($detectedQuery['model'])."\\n";
48
            $output .= "Relation: ".addslashes($detectedQuery['relation'])."\\n";
49
            $output .= "Num-Called: ".$detectedQuery['count']."\\n";
50
            $output .= "\\n";
51
            $output .= 'Call-Stack:\\n';
52
53
            foreach ($detectedQuery['sources'] as $source) {
54
                $output .= "#$source->index $source->name:$source->line\\n";
55
            }
56
        }
57
        $output .= "')";
58
        $output .= '</script>';
59
60
        return $output;
61
    }
62
}
63