Passed
Pull Request — master (#79)
by Mohannad
11:37
created

InteractsWithSourceFiles::normalizeFilename()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace BeyondCode\QueryDetector\Concerns;
4
5
trait InteractsWithSourceFiles
6
{
7
    protected function findSource($stack)
8
    {
9
        $sources = [];
10
11
        foreach ($stack as $index => $trace) {
12
            $sources[] = $this->parseTrace($index, $trace);
13
        }
14
15
        return array_values(array_filter($sources));
16
    }
17
18
    public function parseTrace($index, array $trace)
19
    {
20
        $frame = (object) [
21
            'index' => $index,
22
            'name' => null,
23
            'line' => isset($trace['line']) ? $trace['line'] : '?',
24
        ];
25
26
        if (isset($trace['class']) &&
27
            isset($trace['file']) &&
28
            !$this->fileIsInExcludedPath($trace['file'])
29
        ) {
30
            $frame->name = $this->normalizeFilename($trace['file']);
31
32
            return $frame;
33
        }
34
35
        return false;
36
    }
37
38
    /**
39
     * Check if the given file is to be excluded from analysis
40
     *
41
     * @param string $file
42
     * @return bool
43
     */
44
    protected function fileIsInExcludedPath($file)
45
    {
46
        $excludedPaths = [
47
            '/vendor/laravel/framework/src/Illuminate/Database',
48
            '/vendor/laravel/framework/src/Illuminate/Events',
49
        ];
50
51
        $normalizedPath = str_replace('\\', '/', $file);
52
53
        foreach ($excludedPaths as $excludedPath) {
54
            if (strpos($normalizedPath, $excludedPath) !== false) {
55
                return true;
56
            }
57
        }
58
59
        return false;
60
    }
61
62
    /**
63
     * Shorten the path by removing the relative links and base dir
64
     *
65
     * @param string $path
66
     * @return string
67
     */
68
    protected function normalizeFilename($path): string
69
    {
70
        if (file_exists($path)) {
71
            $path = realpath($path);
72
        }
73
74
        return str_replace(base_path(), '', $path);
75
    }
76
}