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