UnexpectedValueException   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 44
ccs 18
cts 18
cp 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getExceptionMessage() 0 18 5
1
<?php
2
3
namespace Cerbero\Dto\Exceptions;
4
5
use Cerbero\Dto\DtoProperty;
6
use TypeError;
7
8
/**
9
 * Exception thrown when a value set in a DTO property is unexpected.
10
 *
11
 */
12
class UnexpectedValueException extends TypeError implements DtoException
13
{
14
    /**
15
     * The failing DTO property.
16
     *
17
     * @var DtoProperty
18
     */
19
    protected $property;
20
21
    /**
22
     * Instantiate the class.
23
     *
24
     * @param DtoProperty $property
25
     */
26 6
    public function __construct(DtoProperty $property)
27
    {
28 6
        $this->property = $property;
29
30 6
        parent::__construct($this->getExceptionMessage());
31 6
    }
32
33
    /**
34
     * Retrieve the exception message
35
     *
36
     * @return string
37
     */
38 6
    protected function getExceptionMessage(): string
39
    {
40 6
        $name = $this->property->getName();
41 6
        $declaredNames = $this->property->getTypes()->declaredNames;
42 6
        $typeNames = implode("', '", $declaredNames);
43 6
        $types = count($declaredNames) == 1 ? "of type '{$typeNames}'" : "one of these types: '{$typeNames}'";
44 6
        $value = $this->property->getRawValue();
45 6
        $actualType = gettype($value);
46
47 6
        if ($value === null) {
48 3
            $value = 'null';
49 3
        } elseif (is_array($value)) {
50 1
            $value = 'array';
51 2
        } elseif (is_object($value)) {
52 1
            $value = get_class($value);
53
        }
54
55 6
        return "Invalid type: expected '{$name}' to be {$types}. Got `{$value}` ({$actualType}) instead";
56
    }
57
}
58