Passed
Push — master ( 7065f2...e55ca3 )
by Edward
03:45
created

InvalidElementKeyException::getKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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