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\PropertyException; |
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
|
|
|
* @var array |
29
|
|
|
*/ |
30
|
|
|
private $methods = []; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @return array |
34
|
|
|
*/ |
35
|
3 |
|
final public function payload() |
36
|
|
|
{ |
37
|
3 |
|
return $this->payload; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param array $payload |
42
|
|
|
* @param array $required |
43
|
|
|
* |
44
|
|
|
* @throws PropertyException |
45
|
|
|
*/ |
46
|
12 |
|
final protected function setPayload(array $payload, array $required = []) |
47
|
|
|
{ |
48
|
12 |
|
if ($required && ($lost = array_diff($required, array_keys($payload)))) { |
|
|
|
|
49
|
2 |
|
throw PropertyException::noRequiredProperties($lost, $this); |
50
|
|
|
} |
51
|
|
|
|
52
|
10 |
|
$this->analyze(); |
53
|
|
|
|
54
|
10 |
|
foreach ($payload as $name => $value) { |
55
|
10 |
|
if (in_array($name, $this->properties)) { |
56
|
3 |
|
$this->$name = $value; |
57
|
3 |
|
continue; |
58
|
7 |
|
} elseif (($method = 'set'.ucfirst($name)) && in_array($method, $this->methods)) { |
59
|
1 |
|
$this->{$method}($value); |
60
|
1 |
|
continue; |
61
|
|
|
} |
62
|
|
|
|
63
|
6 |
|
throw PropertyException::undefinedProperty($name, $this); |
64
|
4 |
|
} |
65
|
|
|
|
66
|
4 |
|
$this->payload = $payload; |
67
|
4 |
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return array |
71
|
|
|
*/ |
72
|
10 |
|
private function analyze() |
73
|
|
|
{ |
74
|
10 |
|
if (!$this->properties && !$this->methods) { |
75
|
10 |
|
$ref = new \ReflectionClass($this); |
76
|
|
|
|
77
|
10 |
|
$properties = $ref->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED); |
78
|
10 |
|
foreach ($properties as $property) { |
79
|
9 |
|
$this->properties[] = $property->getName(); |
80
|
10 |
|
} |
81
|
|
|
|
82
|
10 |
|
$methods = $ref->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED); |
83
|
10 |
|
foreach ($methods as $method) { |
84
|
10 |
|
$this->methods[] = $method->getName(); |
|
|
|
|
85
|
10 |
|
} |
86
|
10 |
|
} |
87
|
10 |
|
} |
88
|
|
|
} |
89
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.