Passed
Pull Request — master (#88)
by
unknown
12:16
created

MongoUpdateSerialize::processArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
crap 6
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
}