Completed
Push — master ( 404b2c...a94229 )
by Julián
08:43
created

AbstractScalarDTO::checkParameterType()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.4444
c 0
b 0
f 0
cc 8
nc 8
nop 1
1
<?php
2
3
/*
4
 * dto (https://github.com/phpgears/dto).
5
 * General purpose immutable Data Transfer Objects for PHP.
6
 *
7
 * @license MIT
8
 * @link https://github.com/phpgears/dto
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Gears\DTO;
15
16
use Gears\DTO\Exception\InvalidScalarParameterException;
17
use Gears\Immutability\ImmutabilityBehaviour;
18
19
/**
20
 * Abstract immutable and only scalar values Data Transfer Object.
21
 */
22
abstract class AbstractScalarDTO implements DTO
23
{
24
    use ImmutabilityBehaviour, ScalarPayloadBehaviour {
25
        ScalarPayloadBehaviour::__call insteadof ImmutabilityBehaviour;
26
        ScalarPayloadBehaviour::checkParameterType as private scalarCheckParameterType;
27
    }
28
29
    /**
30
     * AbstractSerializableDTO constructor.
31
     *
32
     * @param array<string, mixed> $parameters
33
     */
34
    final protected function __construct(array $parameters)
35
    {
36
        $this->checkImmutability();
37
38
        $this->setPayload($parameters);
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     *
44
     * @param mixed $value
45
     */
46
    final protected function checkParameterType(&$value): void
47
    {
48
        if ($value instanceof DTOCollection) {
49
            $value = \iterator_to_array($value->getElements());
50
        }
51
52
        if (\is_array($value)) {
53
            foreach ($value as $val) {
54
                $this->checkParameterType($val);
55
            }
56
        } elseif ($value !== null && !\is_scalar($value) && !$value instanceof self) {
57
            throw new InvalidScalarParameterException(\sprintf(
58
                'Class %s can only accept scalar payload parameters, %s given',
59
                self::class,
60
                \is_object($value) ? \get_class($value) : \gettype($value)
61
            ));
62
        }
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     *
68
     * @return string[]
69
     */
70
    final protected function getAllowedInterfaces(): array
71
    {
72
        return [DTO::class];
73
    }
74
}
75