InvalidElementKeyException::buildKey()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 13
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\JSON\Data\Value\DecodedJson\Exception;
6
7
use Remorhaz\JSON\Data\Exception\ExceptionInterface;
8
use Remorhaz\JSON\Data\Path\PathAwareInterface;
9
use Remorhaz\JSON\Data\Path\PathInterface;
10
use RuntimeException;
11
use Throwable;
12
13
use function gettype;
14
use function is_int;
15
use function is_string;
16
17
class InvalidElementKeyException extends RuntimeException implements ExceptionInterface, PathAwareInterface
18
{
19
20
    private $key;
21
22
    private $path;
23
24
    /**
25
     * @param mixed $key
26
     * @param PathInterface $path
27
     * @param Throwable|null $previous
28
     */
29
    public function __construct($key, PathInterface $path, Throwable $previous = null)
30
    {
31
        $this->key = $key;
32
        $this->path = $path;
33
        parent::__construct($this->buildMessage(), 0, $previous);
34
    }
35
36
    private function buildMessage(): string
37
    {
38
        return "Invalid element key in decoded JSON: {$this->buildKey()} at {$this->buildPath()}";
39
    }
40
41
    public function getKey()
42
    {
43
        return $this->key;
44
    }
45
46
    public function getPath(): PathInterface
47
    {
48
        return $this->path;
49
    }
50
51
    private function buildKey(): string
52
    {
53
        if (is_string($this->key)) {
54
            return $this->key;
55
        }
56
57
        if (is_int($this->key)) {
58
            return (string) $this->key;
59
        }
60
61
        $type = gettype($this->key);
62
63
        return "<{$type}>";
64
    }
65
66
    private function buildPath(): string
67
    {
68
        return '/' . implode('/', $this->path->getElements());
69
    }
70
}
71