Completed
Push — master ( a94229...729053 )
by Julián
05:22
created

ScalarPayloadBehaviour::setPayloadParameter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 2
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
18
/**
19
 * Scalar payload behaviour.
20
 */
21
trait ScalarPayloadBehaviour
22
{
23
    use PayloadBehaviour {
24
        setPayloadParameter as private defaultSetPayloadParameter;
25
    }
26
27
    /**
28
     * Set payload parameter.
29
     *
30
     * @param string $parameter
31
     * @param mixed  $value
32
     */
33
    private function setPayloadParameter(string $parameter, $value): void
34
    {
35
        $this->checkParameterType($value);
36
37
        $this->defaultSetPayloadParameter($parameter, $value);
38
    }
39
40
    /**
41
     * Check only scalar types allowed.
42
     *
43
     * @param mixed $value
44
     *
45
     * @throws InvalidScalarParameterException
46
     */
47
    final protected function checkParameterType($value): void
48
    {
49
        if (\is_array($value)) {
50
            foreach ($value as $val) {
51
                $this->checkParameterType($val);
52
            }
53
        } elseif ($value !== null && !\is_scalar($value)) {
54
            throw new InvalidScalarParameterException(\sprintf(
55
                'Class "%s" can only accept scalar payload parameters, "%s" given',
56
                self::class,
57
                \is_object($value) ? \get_class($value) : \gettype($value)
58
            ));
59
        }
60
    }
61
}
62