1
|
|
|
<?php |
2
|
|
|
namespace Suricate\Traits; |
3
|
|
|
|
4
|
|
|
trait DBObjectExport |
5
|
|
|
{ |
6
|
|
|
protected $exportedVariables = []; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Define object exported variables |
10
|
|
|
* |
11
|
|
|
* @return DBObject |
12
|
|
|
*/ |
13
|
2 |
|
protected function setExportedVariables() |
14
|
|
|
{ |
15
|
2 |
|
if (count($this->exportedVariables)) { |
16
|
1 |
|
return $this; |
|
|
|
|
17
|
|
|
} |
18
|
|
|
|
19
|
2 |
|
$dbMappingExport = []; |
20
|
2 |
|
foreach ($this->dbVariables as $field) { |
21
|
2 |
|
$dbMappingExport[$field] = $field; |
22
|
|
|
} |
23
|
2 |
|
$this->exportedVariables = $dbMappingExport; |
24
|
|
|
|
25
|
2 |
|
return $this; |
|
|
|
|
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Export DBObject to array |
30
|
|
|
* |
31
|
|
|
* @return array |
32
|
|
|
*/ |
33
|
2 |
|
public function toArray() |
34
|
|
|
{ |
35
|
2 |
|
$this->setExportedVariables(); |
36
|
2 |
|
$result = []; |
37
|
2 |
|
foreach ($this->exportedVariables as $sourceName => $destinationName) { |
38
|
2 |
|
$omitEmpty = false; |
39
|
2 |
|
$castType = null; |
40
|
2 |
|
if (strpos($destinationName, ',') !== false) { |
41
|
1 |
|
$splitted = explode(',', $destinationName); |
42
|
|
|
array_map(function ($item) use (&$castType, &$omitEmpty) { |
43
|
1 |
|
if ($item === 'omitempty') { |
44
|
1 |
|
$omitEmpty = true; |
45
|
1 |
|
return; |
46
|
|
|
} |
47
|
1 |
|
if (substr($item, 0, 5) === 'type:') { |
48
|
1 |
|
$castType = substr($item, 5); |
49
|
|
|
} |
50
|
1 |
|
}, $splitted); |
51
|
|
|
|
52
|
1 |
|
$destinationName = $splitted[0]; |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
if ($destinationName === '-') { |
56
|
1 |
|
continue; |
57
|
|
|
} |
58
|
|
|
|
59
|
2 |
|
if ($omitEmpty && empty($this->$sourceName)) { |
60
|
1 |
|
continue; |
61
|
|
|
} |
62
|
2 |
|
$value = $this->$sourceName; |
63
|
2 |
|
if ($castType !== null) { |
64
|
1 |
|
settype($value, $castType); |
65
|
|
|
} |
66
|
2 |
|
$result[$destinationName] = $value; |
67
|
|
|
} |
68
|
|
|
|
69
|
2 |
|
return $result; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Export DBObject to JSON format |
74
|
|
|
* |
75
|
|
|
* @return string |
76
|
|
|
*/ |
77
|
1 |
|
public function toJson() |
78
|
|
|
{ |
79
|
1 |
|
return json_encode($this->toArray()); |
80
|
|
|
} |
81
|
|
|
} |