CallerStateCollector::collect()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 8
nop 0
dl 0
loc 30
rs 9.2888
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of the reliforp/reli-prof 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 Reli\Lib\Log\StateCollector;
15
16
use Reli\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
            assert(isset($last_logger_frame['file']));
41
            /** @psalm-suppress RedundantCondition */
42
            assert(isset($last_logger_frame['line']));
43
            $result['context'] = [
44
                'file' => $last_logger_frame['file'],
45
                'line' => $last_logger_frame['line'],
46
                'class' => $caller_frame['class'] ?? '',
47
                'function' => $caller_frame['function'] ?? '',
48
                'args' => $caller_frame['args'] ?? '',
49
            ];
50
        }
51
        return $result;
52
    }
53
54
    private function isLoggerFrame(array $frame): bool
55
    {
56
        if ($frame['class'] === Log::class) {
57
            if (in_array($frame['function'], ['log', ...Log::LOG_LEVELS], true)) {
58
                return true;
59
            }
60
        }
61
        return false;
62
    }
63
}
64