Passed
Pull Request — master (#817)
by Aleksei
06:51
created

Trace::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Core\Internal;
6
7
use Closure;
8
use ReflectionFunction;
9
use Spiral\Core\Exception\Traits\ClosureRendererTrait;
10
11
/**
12
 * @internal
13
 */
14
final class Trace implements \Stringable
15
{
16
    private const ARRAY_MAX_LEVEL = 3;
17
18
    use ClosureRendererTrait;
0 ignored issues
show
Bug introduced by
The trait Spiral\Core\Exception\Traits\ClosureRendererTrait requires the property $class which is not provided by Spiral\Core\Internal\Trace.
Loading history...
19
    public readonly ?string $alias;
20
21 742
    public function __construct(
22
        public array $info = [],
23
    ) {
24 742
        $this->alias = $info['alias'] ?? null;
0 ignored issues
show
Bug introduced by
The property alias is declared read-only in Spiral\Core\Internal\Trace.
Loading history...
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
            \is_object($item) => 'instance of ' . $item::class,
43 414
            \is_array($item) => $this->renderArray($item),
44 421
            default => \gettype($item),
45
        };
46
    }
47
48 310
    private function renderArray(array $array, int $level = 0): string
49
    {
50 310
        if ($array === []) {
51
            return '[]';
52
        }
53 310
        if ($level >= self::ARRAY_MAX_LEVEL) {
54
            return 'array';
55
        }
56 310
        $result = [];
57 310
        foreach ($array as $key => $value) {
58 310
            $result[] = \sprintf(
59
                '%s: %s',
60
                $key,
61 310
                \is_array($value)
62 256
                    ? $this->renderArray($value, $level + 1)
63 310
                    : $this->stringifyValue($value),
64
            );
65
        }
66
67 310
        $pad = \str_repeat('  ', $level);
68 310
        return "[\n  $pad" . \implode(",\n  $pad", $result) . "\n$pad]";
69
    }
70
}
71