1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Core\Internal; |
6
|
|
|
|
7
|
|
|
use ReflectionFunction; |
8
|
|
|
use Spiral\Core\Exception\Traits\ClosureRendererTrait; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @internal |
12
|
|
|
*/ |
13
|
|
|
final class Trace implements \Stringable |
14
|
|
|
{ |
15
|
|
|
use ClosureRendererTrait; |
|
|
|
|
16
|
|
|
|
17
|
|
|
private const ARRAY_MAX_LEVEL = 3; |
18
|
|
|
|
19
|
|
|
public readonly ?string $alias; |
20
|
|
|
|
21
|
742 |
|
public function __construct( |
22
|
|
|
public array $info = [], |
23
|
|
|
) { |
24
|
742 |
|
$this->alias = $info['alias'] ?? null; |
|
|
|
|
25
|
|
|
} |
26
|
|
|
|
27
|
421 |
|
public function __toString(): string |
28
|
|
|
{ |
29
|
421 |
|
$info = []; |
30
|
421 |
|
foreach ($this->info as $key => $item) { |
31
|
421 |
|
$info[] = "$key: {$this->stringifyValue($item)}"; |
32
|
|
|
} |
33
|
421 |
|
return \implode("\n", $info); |
34
|
|
|
} |
35
|
|
|
|
36
|
421 |
|
private function stringifyValue(mixed $item): string |
37
|
|
|
{ |
38
|
|
|
return match (true) { |
39
|
421 |
|
\is_string($item) => "'$item'", |
40
|
414 |
|
\is_scalar($item) => \var_export($item, true), |
41
|
414 |
|
$item instanceof \Closure => $this->renderClosureSignature(new \ReflectionFunction($item)), |
42
|
414 |
|
$item instanceof \ReflectionFunctionAbstract => $this->renderClosureSignature($item), |
43
|
414 |
|
$item instanceof \UnitEnum => $item::class . "::$item->name", |
44
|
414 |
|
\is_object($item) => 'instance of ' . $item::class, |
45
|
414 |
|
\is_array($item) => $this->renderArray($item), |
46
|
421 |
|
default => \gettype($item), |
47
|
|
|
}; |
48
|
|
|
} |
49
|
|
|
|
50
|
310 |
|
private function renderArray(array $array, int $level = 0): string |
51
|
|
|
{ |
52
|
310 |
|
if ($array === []) { |
53
|
|
|
return '[]'; |
54
|
|
|
} |
55
|
310 |
|
if ($level >= self::ARRAY_MAX_LEVEL) { |
56
|
|
|
return 'array'; |
57
|
|
|
} |
58
|
310 |
|
$result = []; |
59
|
310 |
|
foreach ($array as $key => $value) { |
60
|
310 |
|
$result[] = \sprintf( |
61
|
|
|
'%s: %s', |
62
|
|
|
$key, |
63
|
310 |
|
\is_array($value) |
64
|
256 |
|
? $this->renderArray($value, $level + 1) |
65
|
310 |
|
: $this->stringifyValue($value), |
66
|
|
|
); |
67
|
|
|
} |
68
|
|
|
|
69
|
310 |
|
$pad = \str_repeat(' ', $level); |
70
|
310 |
|
return "[\n $pad" . \implode(",\n $pad", $result) . "\n$pad]"; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|