Completed
Push — master ( 488797...ae2a4f )
by Marcel
10s
created

Console::boot()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 4
Ratio 100 %

Importance

Changes 0
Metric Value
dl 4
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace BeyondCode\QueryDetector\Outputs;
4
5
use Illuminate\Support\Collection;
6
use Symfony\Component\HttpFoundation\Response;
7
8 View Code Duplication
class Console implements Output
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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(\'".$detectedQuery['relation']."\')\" to eager-load this relation.";
46
            $output .= "\\n";
47
        }
48
        $output .= "')";
49
        $output .= '</script>';
50
51
        return $output;
52
    }
53
}
54