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) { |
|
|
|
|
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
|
|
|
|
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.