Unbound::__toString()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
c 0
b 0
f 0
rs 10
cc 3
nc 3
nop 0
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 implode;
13
use function sprintf;
14
15
/**
16
 * Exception thrown when a binding is not found
17
 *
18
 * Message format: '{type}-{name}' in file:line ($var)
19
 *
20
 * Examples:
21
 * - "'FooInterface-' in file.php:10 ($foo)" - FooInterface with no name
22
 * - "'FooInterface-db' in file.php:10 ($foo)" - FooInterface with name 'db'
23
 * - "'-db' in file.php:10 ($foo)" - no type with name 'db'
24
 */
25
class Unbound extends LogicException implements ExceptionInterface
26
{
27
    public function __toString(): string
28
    {
29
        $messages = [sprintf("- %s\n", $this->getMessage())];
30
        $e = $this->getPrevious();
31
        if (! $e instanceof Exception) {
0 ignored issues
show
introduced by
$e is always a sub-type of Exception.
Loading history...
32
            return $this->getMainMessage($this);
33
        }
34
35
        if ($e instanceof self) {
36
            return $this->buildMessage($e, $messages) . "\n" . $e->getTraceAsString();
37
        }
38
39
        return parent::__toString();
40
    }
41
42
    /**
43
     * @param array<int, string> $msg
44
     */
45
    private function buildMessage(self $e, array $msg): string
46
    {
47
        $lastE = $e;
48
        while ($e instanceof self) {
49
            $msg[] = sprintf("- %s\n", $e->getMessage());
50
            $lastE = $e;
51
            $e = $e->getPrevious();
52
        }
53
54
        array_pop($msg);
55
        $msg = array_reverse($msg);
56
57
        return $this->getMainMessage($lastE) . implode('', $msg);
58
    }
59
60
    /**
61
     * @psalm-pure
62
     */
63
    private function getMainMessage(self $e): string
64
    {
65
        return sprintf(
66
            "exception '%s' with message '%s'\n",
67
            $e::class,
68
            $e->getMessage()
69
        );
70
    }
71
}
72