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

BSONSerialize::bsonArraySerialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
namespace Fathomminds\Rest\Database\MongoDB;
3
4
use Fathomminds\Rest\Schema\TypeValidators\ArrayValidator;
5
use Fathomminds\Rest\Schema\TypeValidators\MongoIdValidator;
6
use MongoDB\BSON\ObjectId;
7
use MongoDB\Model\BSONArray;
8
use MongoDB\Model\BSONDocument;
9
10
11
class BSONSerialize
12
{
13
    public function serializeObject($res) {
14
        if (empty($res)) {
15
            return null;
16
        }
17
        if (!is_object($res)) {
18
            return $res;
19
        }
20
        $className = get_class($res);
21
        print($className . "\n");
22
        if ($className === ObjectId::class) {
23
            return (string)$res;
24
        }
25
        if ($className === BSONDocument::class) {
26
            return $this->bsonDocumentSerialize($res);
27
        }
28
        if ($className === BSONArray::class) {
29
            return $this->bsonArraySerialize($res);
30
        }
31
        return $res;
32
    }
33
34
    private function bsonDocumentSerialize($document) {
35
        $res = $document->bsonSerialize();
36
        $resProps = ($res);
37
        foreach ($resProps as $propName => $propValue) {
38
            $res->$propName = $this->serializeObject($propValue);
39
        }
40
        return $res;
41
    }
42
43
    private function bsonArraySerialize($array) {
44
        $res = $array->bsonSerialize();
45
        foreach ($res as $key => $item) {
46
            $res[$key] = $this->serializeObject($item);
47
        }
48
        return $res;
49
    }
50
}