Completed
Push — master ( 3e0ad4...103643 )
by Peter
04:13
created

PayloadTrait::setPayload()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 12
1
<?php
2
3
/**
4
 * GpsLab component.
5
 *
6
 * @author    Peter Gribanov <[email protected]>
7
 * @copyright Copyright (c) 2011, Peter Gribanov
8
 * @license   http://opensource.org/licenses/MIT
9
 */
10
11
namespace GpsLab\Component\Payload;
12
13
use GpsLab\Component\Payload\Exception\UndefinedPropertyException;
14
15
trait PayloadTrait
16
{
17
    /**
18
     * @var array
19
     */
20
    private $payload = [];
21
22
    /**
23
     * @var array
24
     */
25
    private $properties = [];
26
27
    /**
28
     * @return array
29
     */
30
    final public function payload()
31
    {
32
        return $this->payload;
33
    }
34
35
    /**
36
     * @param array $payload
37
     */
38
    final protected function setPayload(array $payload)
39
    {
40
        foreach ($payload as $name => $value) {
41
            if (!in_array($name, $this->getProperties())) {
42
                throw UndefinedPropertyException::propertyOfClass($name, $this);
43
            }
44
45
            $this->$name = $value;
46
        }
47
48
        $this->payload = $payload;
49
    }
50
51
    /**
52
     * @return array
53
     */
54
    private function getProperties()
55
    {
56
        if (!$this->properties) {
57
            $ref = new \ReflectionClass($this);
58
            $properties = $ref->getProperties(\ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PUBLIC);
59
            foreach ($properties as $property) {
60
                $this->properties[] = $property->getName();
61
            }
62
        }
63
64
        return $this->properties;
65
    }
66
}
67