InvalidValueForValueObjectException::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
cc 3
eloc 11
c 3
b 1
f 1
nc 4
nop 2
dl 0
loc 15
rs 9.9
1
<?php
2
3
4
namespace Apie\ValueObjects\Exceptions;
5
6
use Apie\Core\Exceptions\ApieException;
7
use Apie\Core\Exceptions\LocalizationableException;
8
use Apie\Core\Exceptions\LocalizationInfo;
9
use ReflectionClass;
10
11
/**
12
 * Exceptions thrown by value Apie value objects to indicate the value is not correct for the value object.
13
 */
14
class InvalidValueForValueObjectException extends ApieException implements LocalizationableException
15
{
16
    /**
17
     * @var string
18
     */
19
    private $name;
20
21
    /**
22
     * @var mixed
23
     */
24
    private $value;
25
26
    public function __construct($value, $valueObject)
27
    {
28
        $refl = new ReflectionClass($valueObject);
29
        $this->name = strtolower((string) preg_replace('/(?<!^)[A-Z]/', '_$0', $refl->getShortName()));
30
        $this->value = $value;
31
        $displayValue = $value;
32
        if (is_object($displayValue)) {
33
            $displayValue = 'Object ' . get_class($displayValue);
34
        }
35
        if (is_array($value)) {
36
            $displayValue = 'array '. json_encode($value);
37
        }
38
        parent::__construct(
39
            422,
40
            '"' . $displayValue . '" is not a valid value for value object ' . $this->name
41
        );
42
    }
43
44
    public function getI18n(): LocalizationInfo
45
    {
46
        return new LocalizationInfo(
47
            'validation.format',
48
            [
49
                'name' => $this->name,
50
                'value' => $this->value,
51
            ]
52
        );
53
    }
54
}
55