Passed
Push — master ( 76b76b...ca78d8 )
by Edward
02:11
created

InvalidElementKeyException::buildKey()   A

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
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\Exception\PathAwareExceptionTrait;
11
use Remorhaz\JSON\Data\Path\PathAwareInterface;
12
use Remorhaz\JSON\Data\Path\PathInterface;
13
use RuntimeException;
14
use Throwable;
15
16
class InvalidElementKeyException extends RuntimeException implements ExceptionInterface, PathAwareInterface
17
{
18
19
    use PathAwareExceptionTrait;
20
21
    private $key;
22
23
    /**
24
     * @param mixed $key
25
     * @param PathInterface $path
26
     * @param Throwable|null $previous
27
     */
28
    public function __construct($key, PathInterface $path, Throwable $previous = null)
29
    {
30
        $this->key = $key;
31
        $this->path = $path;
32
        parent::__construct($this->buildMessage(), 0, $previous);
33
    }
34
35
    private function buildMessage(): string
36
    {
37
        return "Invalid element key in decoded JSON: {$this->buildKey()} at {$this->buildPath()}";
38
    }
39
40
    public function getKey()
41
    {
42
        return $this->key;
43
    }
44
45
    private function buildKey(): string
46
    {
47
        if (is_string($this->key)) {
48
            return $this->key;
49
        }
50
51
        if (is_int($this->key)) {
52
            return (string) $this->key;
53
        }
54
55
        $type = gettype($this->key);
56
57
        return "<{$type}>";
58
    }
59
}
60