InvalidElementKeyException   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 52
rs 10
c 1
b 0
f 0
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getPath() 0 3 1
A buildMessage() 0 3 1
A __construct() 0 5 1
A buildPath() 0 3 1
A buildKey() 0 13 3
A getKey() 0 3 1
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