1 | <?php |
||
12 | abstract class base_entity |
||
13 | { |
||
14 | /** @var array */ |
||
15 | protected $db_fields = array(); |
||
16 | |||
17 | /** @var array */ |
||
18 | protected $required_fields = array(); |
||
19 | |||
20 | /** |
||
21 | * Populate the entity with data |
||
22 | */ |
||
23 | 159 | public function __construct(array $data) |
|
24 | { |
||
25 | 159 | foreach ($data as $name => $value) |
|
26 | { |
||
27 | 118 | $mutator = 'set_' . $name; |
|
28 | 118 | $this->$mutator($value); |
|
29 | 159 | } |
|
30 | 159 | } |
|
31 | |||
32 | 146 | public function __call($name, $args) |
|
51 | |||
52 | /** |
||
53 | * Get an associative array with the values assigned to the fields of the entity, ready for display |
||
54 | */ |
||
55 | 57 | public function to_array() |
|
56 | { |
||
57 | 57 | $attributes = $this->_get_attributes(); |
|
58 | |||
59 | 57 | $data = array(); |
|
60 | 57 | foreach ($attributes as $attribute) |
|
61 | { |
||
62 | 57 | $accessor = 'get_' . $attribute; |
|
63 | 57 | $data[$attribute] = $this->$accessor(); |
|
64 | 57 | } |
|
65 | 57 | unset($data['db_fields'], $data['required_fields']); |
|
66 | |||
67 | 57 | return $data; |
|
68 | } |
||
69 | |||
70 | /** |
||
71 | * Get an associative array with the raw values assigned to the fields of the entity, ready for storage |
||
72 | */ |
||
73 | 46 | public function to_db() |
|
74 | { |
||
75 | 46 | $this->_check_required(); |
|
76 | |||
77 | 41 | $db_data = array(); |
|
78 | 41 | foreach ($this->db_fields as $attribute) |
|
79 | { |
||
80 | 41 | $type = $this->_get_property_type($attribute); |
|
81 | 41 | if (in_array($type, array('boolean', 'integer', 'string'))) |
|
82 | 41 | { |
|
83 | 41 | $db_data[$attribute] = $this->$attribute; |
|
84 | 41 | } |
|
85 | 41 | } |
|
86 | |||
87 | 41 | return $db_data; |
|
88 | } |
||
89 | |||
90 | 146 | protected function _get_attributes() |
|
94 | |||
95 | 146 | protected function _attribute_exists($name) |
|
96 | { |
||
97 | 146 | if (in_array(strtolower($name), $this->_get_attributes())) |
|
102 | |||
103 | 46 | protected function _check_required() |
|
113 | |||
114 | 121 | protected function _validate_attribute($name, $value) |
|
115 | { |
||
116 | 121 | $type = $this->_get_property_type($name); |
|
117 | |||
118 | 121 | if (in_array($type, array('array', 'boolean', 'float', 'integer', 'string'))) |
|
119 | 121 | { |
|
120 | 116 | settype($value, $type); |
|
121 | 116 | return $value; |
|
122 | } |
||
123 | |||
124 | 35 | if ($type === false || !$value instanceof $type) |
|
125 | 35 | { |
|
126 | 2 | throw new \blitze\sitemaker\exception\unexpected_value(array($name, 'INVALID_TYPE')); |
|
127 | } |
||
128 | |||
129 | 33 | return $value; |
|
130 | } |
||
131 | |||
132 | 124 | protected function _get_property_type($name) |
|
142 | } |
||
143 |