Passed
Pull Request — master (#51)
by Shinji
32:54
created

CallerStateCollector::collect()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 5
eloc 18
c 2
b 1
f 1
nc 8
nop 0
dl 0
loc 27
rs 9.3554
1
<?php
2
3
/**
4
 * This file is part of the sj-i/php-profiler package.
5
 *
6
 * (c) sji <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace PhpProfiler\Lib\Log\StateCollector;
15
16
use PhpProfiler\Lib\Log\Log;
17
18
use function debug_backtrace;
19
20
final class CallerStateCollector implements StateCollector
21
{
22
    public function collect(): array
23
    {
24
        $backtrace = debug_backtrace(limit: 5);
25
26
        $last_logger_frame = [];
27
        $caller_frame = [];
28
29
        foreach ($backtrace as $frame) {
30
            if ($this->isLoggerFrame($frame)) {
31
                $last_logger_frame = $frame;
32
            } elseif ($last_logger_frame) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $last_logger_frame of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
33
                $caller_frame = $frame;
34
                break;
35
            }
36
        }
37
38
        $result = [];
39
        if ($last_logger_frame) {
40
            $result['context'] = [
41
                'file' => $last_logger_frame['file'],
42
                'line' => $last_logger_frame['line'],
43
                'class' => $caller_frame['class'] ?? '',
44
                'function' => $caller_frame['function'] ?? '',
45
                'args' => $caller_frame['args'] ?? '',
46
            ];
47
        }
48
        return $result;
49
    }
50
51
    private function isLoggerFrame(array $frame): bool
52
    {
53
        if ($frame['class'] === Log::class) {
54
            if (in_array($frame['function'], ['log', ...Log::LOG_LEVELS], true)) {
55
                return true;
56
            }
57
        }
58
        return false;
59
    }
60
}
61