Passed
Pull Request — master (#1222)
by Aleksei
12:41
created

TracedContainerException::createStatic()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 9
ccs 8
cts 8
cp 1
rs 10
cc 2
nc 1
nop 3
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Core\Exception\Container;
6
7
use Spiral\Core\Internal\Tracer;
8
9
/**
10
 * Exception that contains trace of resolving.
11
 */
12
class TracedContainerException extends ContainerException
13
{
14
    protected array $containerTrace = [];
15
    protected string $originalMessage = '';
16
17 791
    public function __construct(string $message = '', int $code = 0, ?\Throwable $previous = null)
18
    {
19 791
        $this->originalMessage = $message;
20 791
        parent::__construct($message, $code, $previous);
21
    }
22
23
    /**
24
     * @internal
25
     */
26 791
    public static function createWithTrace(
27
        string $message,
28
        array $trace = [],
29
        ?\Throwable $previous = null,
30
    ): static {
31
        // Merge traces
32 791
        if ($previous instanceof self) {
33 15
            $merge = $previous->containerTrace;
34 15
            if ($trace !== [] && $merge !== []) {
35
                // merge lat element of $traces with first element of $merge
36 15
                \array_push($trace[\count($trace) - 1], ...$merge[0]);
37 15
                unset($merge[0]);
38
            }
39
40 15
            $trace = \array_merge($trace, $merge);
41 15
            $message = "$message\n{$previous->originalMessage}";
42
        }
43
44 791
        return static::createStatic($message, $trace, $previous);
45
    }
46
47 791
    protected static function createStatic(string $message, array $trace, ?\Throwable $previous): static
48
    {
49 791
        $result = new static(
50 791
            $message . ($trace === [] ? '' : "\nResolving trace:\n" . Tracer::renderTraceList($trace)),
51 791
            previous: $previous,
52 791
        );
53 791
        $result->originalMessage = $message;
54 791
        $result->containerTrace = $trace;
55 791
        return $result;
56
    }
57
}
58