1
|
|
|
<?php |
2
|
|
|
namespace Fathomminds\Rest\Database\MongoDB; |
3
|
|
|
|
4
|
|
|
|
5
|
|
|
use MongoDB\BSON\ObjectId; |
6
|
|
|
|
7
|
|
|
class MongoUpdateSerialize |
8
|
|
|
{ |
9
|
|
|
public function serialize($value) |
10
|
|
|
{ |
11
|
|
|
if (!is_object($value)) { |
12
|
|
|
return $value; |
13
|
|
|
} |
14
|
|
|
return (object)$this->processObject($value, ""); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
private function processObject($object, $prefix) |
18
|
|
|
{ |
19
|
|
|
$res = []; |
20
|
|
|
$props = get_object_vars($object); |
21
|
|
|
foreach ($props as $propName => $propValue) { |
22
|
|
|
$res = array_merge($res, $this->processField($prefix, $propName, $propValue)); |
23
|
|
|
} |
24
|
|
|
return $res; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
private function processArray($array, $prefix) |
28
|
|
|
{ |
29
|
|
|
$res = []; |
30
|
|
|
foreach ($array as $itemIdx => $itemValue) { |
31
|
|
|
$res = array_merge($res, $this->processField($prefix, $itemIdx, $itemValue)); |
32
|
|
|
} |
33
|
|
|
return $res; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
private function processField($prefix, $fieldName, $fieldValue) |
37
|
|
|
{ |
38
|
|
|
if (is_object($fieldValue)) { |
39
|
|
|
if (get_class($fieldValue) === ObjectId::class) { |
40
|
|
|
return[ |
41
|
|
|
$this->getPrefix($prefix, $fieldName) => $fieldValue |
42
|
|
|
]; |
43
|
|
|
} |
44
|
|
|
return $this->processObject($fieldValue, $this->getPrefix($prefix, $fieldName)); |
45
|
|
|
} |
46
|
|
|
if (is_array($fieldValue)) { |
47
|
|
|
return $this->processArray($fieldValue, $this->getPrefix($prefix, $fieldName)); |
48
|
|
|
} |
49
|
|
|
return [ |
50
|
|
|
$this->getPrefix($prefix, $fieldName) => $fieldValue |
51
|
|
|
]; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function getPrefix($prefix, $propName) |
55
|
|
|
{ |
56
|
|
|
if (empty($prefix)) { |
57
|
|
|
return $propName; |
58
|
|
|
} |
59
|
|
|
return $prefix . "." . $propName; |
60
|
|
|
} |
61
|
|
|
} |