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

InteractsWithSourceFiles   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 26
c 1
b 0
f 0
dl 0
loc 70
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A parseTrace() 0 18 5
A normalizeFilename() 0 7 2
A findSource() 0 9 2
A fileIsInExcludedPath() 0 16 3
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
}