Unbound   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 19
c 0
b 0
f 0
dl 0
loc 44
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 13 3
A buildMessage() 0 13 2
A getMainMessage() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Di\Exception;
6
7
use Exception;
8
use LogicException;
9
10
use function array_pop;
11
use function array_reverse;
12
use function get_class;
13
use function implode;
14
use function sprintf;
15
16
class Unbound extends LogicException implements ExceptionInterface
17
{
18
    public function __toString(): string
19
    {
20
        $messages = [sprintf("- %s\n", $this->getMessage())];
21
        $e = $this->getPrevious();
22
        if (! $e instanceof Exception) {
0 ignored issues
show
introduced by
$e is always a sub-type of Exception.
Loading history...
23
            return $this->getMainMessage($this);
24
        }
25
26
        if ($e instanceof self) {
27
            return $this->buildMessage($e, $messages) . "\n" . $e->getTraceAsString();
28
        }
29
30
        return parent::__toString();
31
    }
32
33
    /**
34
     * @param array<int, string> $msg
35
     */
36
    private function buildMessage(self $e, array $msg): string
37
    {
38
        $lastE = $e;
39
        while ($e instanceof self) {
40
            $msg[] = sprintf("- %s\n", $e->getMessage());
41
            $lastE = $e;
42
            $e = $e->getPrevious();
43
        }
44
45
        array_pop($msg);
46
        $msg = array_reverse($msg);
47
48
        return $this->getMainMessage($lastE) . implode('', $msg);
49
    }
50
51
    /**
52
     * @psalm-pure
53
     */
54
    private function getMainMessage(self $e): string
55
    {
56
        return sprintf(
57
            "exception '%s' with message '%s'\n",
58
            get_class($e),
59
            $e->getMessage()
60
        );
61
    }
62
}
63