Passed
Push — master ( f32e65...4e94c9 )
by Michael
02:27
created

NotIterableAttribute::getDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Mapper\Handler\Exception;
5
6
use Mikemirten\Component\JsonApi\Mapper\Definition\Attribute;
7
8
/**
9
 * Exception of non-iterable value of attribute declared as "many" (an iterable container).
10
 *
11
 * @package Mikemirten\Component\JsonApi\Mapper\Handler\Exception
12
 */
13
class NotIterableAttribute extends MappingHandlerException
14
{
15
    /**
16
     * @var Attribute
17
     */
18
    protected $definition;
19
20
    /**
21
     * NotIterableAttribute constructor.
22
     *
23
     * @param Attribute $attribute
24
     * @param mixed     $value
25
     */
26 1
    public function __construct(Attribute $attribute, $value)
27
    {
28 1
        $message = sprintf(
29 1
            'Attribute "%s" declared as many (an iterable container) contains %s which cannot be iterated.',
30 1
            $attribute->getName(),
31 1
            $this->resolveTypeDescription($value)
32
        );
33
34 1
        parent::__construct($message);
35 1
    }
36
37
    /**
38
     * Get definition of attribute caused the issue
39
     *
40
     * @return Attribute
41
     */
42
    public function getDefinition(): Attribute
43
    {
44
        return $this->definition;
45
    }
46
47
    /**
48
     * Resolve description of value's type
49
     *
50
     * @param  $value
51
     * @return string
52
     */
53 1
    protected function resolveTypeDescription($value): string
54
    {
55 1
        $type = gettype($value);
56
57 1
        if ($type === 'object') {
58
            return 'an instance of ' . get_class($value);
59
        }
60
61 1
        if ($type === 'integer') {
62 1
            return 'an integer';
63
        }
64
65
        return 'a ' . $type;
66
    }
67
}