Completed
Push — master ( 22860b...81e1d8 )
by Alessandro
02:32
created

MongoQuerySerializer::serialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php declare(strict_types = 1);
2
3
namespace Facile\MongoDbBundle\DataCollector;
4
5
use Facile\MongoDbBundle\Models\Query;
6
7
/**
8
 * Class MongoQuerySerializer
9
 * @internal
10
 */
11
final class MongoQuerySerializer
12
{
13
    /**
14
     * @param Query $query
15
     */
16 4
    public static function serialize(Query $query)
17
    {
18 4
        $query->setFilters(self::prepareUnserializableData($query->getFilters()));
19 4
        $query->setData(self::prepareUnserializableData($query->getData()));
20 4
        $query->setOptions(self::prepareUnserializableData($query->getOptions()));
21 4
    }
22
23
    /**
24
     * @param array|object $data
25
     *
26
     * @return array|object
27
     */
28 4
    private static function prepareUnserializableData($data)
29
    {
30 4
        foreach ($data as $key => $item) {
31 4
            $data[$key] = self::prepareItemData($item);
32
        }
33
34 4
        return $data;
35
    }
36
37
    /**
38
     * @param mixed $item
39
     *
40
     * @return mixed
41
     */
42 4
    private static function prepareItemData($item)
43
    {
44 4
        if (method_exists($item, 'getArrayCopy')) {
45 2
            return self::prepareUnserializableData($item->getArrayCopy());
46
        }
47
48 3
        if (method_exists($item, 'toDateTime')) {
49 1
            return 'ISODate("'.$item->toDateTime()->format('c').'")';
50
        }
51
52 2
        if (method_exists($item, '__toString')) {
53
            return $item->__toString();
54
        }
55
56 2
        if (method_exists($item, 'bsonSerialize')) {
57
            return $item->bsonSerialize();
58
        }
59
60 2
        if (is_array($item) || is_object($item)) {
61 1
            return self::prepareUnserializableData((array) $item);
62
        }
63
64 1
        return $item;
65
    }
66
67
}
68