-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonizer.php
More file actions
78 lines (65 loc) · 1.8 KB
/
Jsonizer.php
File metadata and controls
78 lines (65 loc) · 1.8 KB
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
<?php
class Jsonizer {
public function toJson($model) {
$types = array();
if (method_exists($model, 'getJsonTypes')) {
$types = array_merge($types, $model->getJsonTypes());
}
$meta = $model->metaData;
$obj = array();
if (method_exists($model, 'humanReadableName')) {
$obj['name'] = $model->humanReadableName();
}
$excl = array();
if (method_exists($model, 'getJsonExcludedAttributes')) {
$excl = $model->getJsonExcludedAttributes();
}
foreach ($model->getAttributes() as $key => $value) {
$jsonKey;
$jsonValue;
if (preg_match('/Id$/', $key)) {
$relation = preg_replace('/Id$/', '', $key);
if ($meta->hasRelation($relation) && method_exists($model->$relation, 'getName')) {
$jsonKey = $relation;
$jsonValue = $model->$relation->getName();
}
}
else if (isset($types[$key])) {
$jsonKey = $key;
switch ($types[$key]) {
case 'boolean':
$jsonValue = $value ? true : false;
break;
case 'number':
$jsonValue = floatval($value);
break;
default:
$jsonValue = $value;
break;
}
}
else if (in_array($key, $excl)) {
}
else {
$jsonKey = $key;
$jsonValue = $value;
}
if ($jsonKey !== null) {
$obj[$jsonKey] = $jsonValue;
}
}
if (method_exists($model, 'toJson')) {
$obj = array_merge($obj, $model->toJson());
}
/*
foreach ($meta->relations as $key => $value) {
if (get_class($value) === 'CBelongsToRelation') {
$name = $value->name;
$obj[$key] = $this->toJson($model->$name);
}
}
*/
return $obj;
}
}
?>