Passed
Push — master ( 4e94c9...4bfcda )
by Michael
02:19
created

NotIterableAttribute::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 2
crap 1
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 $definition
24
     * @param mixed     $value
25
     */
26 6
    public function __construct(Attribute $definition, $value)
27
    {
28 6
        $this->definition = $definition;
29
30 6
        $message = sprintf(
31 6
            'Attribute "%s" declared as many (an iterable container) contains %s which cannot be iterated.',
32 6
            $definition->getName(),
33 6
            $this->resolveTypeDescription($value)
34
        );
35
36 6
        parent::__construct($message);
37 6
    }
38
39
    /**
40
     * Get definition of attribute caused the issue
41
     *
42
     * @return Attribute
43
     */
44
    public function getDefinition(): Attribute
45
    {
46
        return $this->definition;
47
    }
48
49
    /**
50
     * Resolve description of value's type
51
     *
52
     * @param  $value
53
     * @return string
54
     */
55 6
    protected function resolveTypeDescription($value): string
56
    {
57 6
        $type = gettype($value);
58
59 6
        if ($type === 'object') {
60
            return 'an instance of ' . get_class($value);
61
        }
62
63 6
        if ($type === 'integer') {
64 4
            return 'an integer';
65
        }
66
67 2
        return 'a ' . $type;
68
    }
69
}