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

BSONSerialize   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 0
dl 0
loc 40
ccs 0
cts 25
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B serializeObject() 0 20 6
A bsonDocumentSerialize() 0 8 2
A bsonArraySerialize() 0 7 2
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
}