-
Notifications
You must be signed in to change notification settings - Fork 5
/
ModelBase.php
executable file
·269 lines (251 loc) · 8.18 KB
/
ModelBase.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<?
namespace Phalcon;
use Phalcon\Mvc\Model\Behavior\Timestampable,
Phalcon\Mvc\Model\MetaData,
Phalcon\Builder\Form,
Phalcon\Annotations\Reader,
Phalcon\Annotations\Reflection,
Phalcon\Mvc\Model,
Phalcon\Support\Helper\Str\Camelize,
Phalcon\Support\Helper\Str\Uncamelize;
/**
* Base class of all models
*/
class ModelBase extends Model{
/**
* Get descriptions of all columns of the model
*
* @param null|array $excludes=[] List of the columns to exclude
*
* @return array Columns description
*/
public static function getColumnsDescription(null|array $excludes=[]):array{
$reader = new Reader();
$parsing = $reader->parse(get_called_class());
$reflector = new Reflection($parsing);
$descriptions = [];
foreach($reflector->getPropertiesAnnotations() as $annotations){
foreach($annotations->getAnnotations() as $annotation){
if($annotation->getName() !== 'Column'){
continue;
}
$args = $annotation->getArguments();
if(!in_array($args['column'], $excludes)){
$descriptions[self::getPrefix().'_'.$args['column']] = $args;
}
}
}
return $descriptions;
}
/**
* Get field type
*
* @param string $field Name of the field
*
* @return string|false Type of the field or false if not found
*/
public static function getType(string $field):string|false{
$model = get_called_class();
foreach($model::getColumnsDescription() as $name => $option){
if($name === $field){
return $option['type'];
}
}
return false;
}
/**
* Get all relation by type
*
* @param string $type Type of the relation
*
* @return array Relations found
*/
public static function returnRelations(string $type):array{
$type = 'get'.(new Camelize())((new Uncamelize())($type));
$relations=[];
$model = get_called_class();
$model = new $model();
foreach($model->getModelsManager()->$type($model) as $relation){
if($type === 'getBelongsTo'){
$relations[$relation->getFields()] = [
'model' => $relation->getReferencedModel(),
'field' => $relation->getReferencedFields()
];
} else {
if(!isset($relations[$relation->getFields()])){
$relations[$relation->getFields()] = [];
}
$relations[$relation->getFields()][] = [
'model' => $relation->getReferencedModel(),
'field' => $relation->getReferencedFields()
];
}
}
return $relations;
}
/**
* Set relations in \Phalcon\Builder\Form $relations static variable
*
* @param string $type Type of the relation
*
* @return void
*/
public static function getRelations(string $type):void{
Form::$relations = self::returnRelations($type);
}
/**
* Check if current model has a hasOne relation with the target, if true add field in \Phalcon\Builder\Form $excludes static variable
*
* @param string $target Name of the model to check with
*
* @return bool Result of the check
*/
public static function checkHasOne(string $target):bool{
$model = get_called_class();
$model = new $model();
foreach($model->getModelsManager()->getHasOne($model) as $relation){
if($relation->getReferencedModel() === $target){
Form::$excludes[] = substr($relation->getReferencedFields(), strpos($relation->getReferencedFields(), '_')+1);
return true;
}
}
return false;
}
/**
* Get referenced field(s) with a model having hasOne relation, return false if not found
*
* @param string $model Name of the model to get whith
*
* @return string|array|false Field name or list or false if not found
*/
public static function getReferencedField(string $model):string|array|false{
$model = get_called_class();
$model = new $model();
foreach($model->getModelsManager()->getHasOne($model) as $relation){
if($relation->getReferencedModel() === $model){
return $relation->getReferencedFields();
}
}
return false;
}
/**
* Get columns map
*
* @return array Columns map
*/
public static function getColumnsMap():array{
$model = get_called_class();
$model = new $model();
return $model->getModelsMetaData()->getColumnMap($model);
}
/**
* Merge params with columns description
*
* @param array $params Params to add to columns description
*
* @return array Result of the merge
*/
public static function filterParams(array $params):array{
$model = get_called_class();
return array_intersect_key($params, $model::getColumnsDescription());
}
/**
* Get erros from a PHQL query
*
* @param null|array $errors=[] Errors to merge with
*
* @return array Errors of the query
*/
public function getErrors(null|array $errors=[]):array{
foreach($this->getMessages() as $message){
$errors[] = $message->getMessage();
}
return $errors;
}
/**
* Get model prefix
*
* @return string Model prefix
*/
public static function getPrefix():string{
$model = get_called_class();
$prefix = '';
foreach(explode('_', (new Uncamelize())($model)) as $name){
$prefix .= $name[0].$name[1];
}
return $prefix;
}
/**
* Get required columns
*
* @return array List of all required columns
*/
public static function getRequired():array{
$columns = [];
$prefix = self::getPrefix();
foreach(self::getColumnsDescription() as $name => $column){
if(!$column['nullable'] && !isset($column['default']) && (!isset($column['extra']) || $column['extra'] !== 'auto_increment') && !in_array($name, [$prefix.'_created_at', $prefix.'_updated_at'])){
$columns[] = $name;
}
}
return $columns;
}
/**
* Get primary key
*
* @return array Prmary key
*/
public static function getPrimaryKey():string{
$model = get_called_class();
$model = new $model();
return $model->getModelsMetaData()->getPrimaryKeyAttributes($model)[0];
}
/**
* Get the field name mapped
*
* @param string $field Field name to map
*
* @return string Field name mapped
*/
public static function getMapped(string $field):string{
$model = get_called_class();
$model = new $model();
return $model->getModelsMetaData()->readColumnMapIndex($model, MetaData::MODELS_COLUMN_MAP)[$field];
}
/**
* Add automatic values for fields created_at and updated_at on creation and update
*
* @return void
*/
public function initialize():void{
$prefix = self::getPrefix();
if(property_exists($this, $prefix.'_created_at')){
$this->addBehavior(new Timestampable(
[
'beforeCreate' => [
'field' => $prefix.'_created_at',
'format' => 'Y-m-d H:i:s'
]
]
));
}
if(property_exists($this, $prefix.'_updated_at')){
$this->addBehavior(new Timestampable(
[
'beforeCreate' => [
'field' => $prefix.'_updated_at',
'format' => 'Y-m-d H:i:s'
]
]
));
$this->addBehavior(new Timestampable(
[
'beforeUpdate' => [
'field' => $prefix.'_updated_at',
'format' => 'Y-m-d H:i:s'
]
]
));
}
}
}