Completed
Push — master ( 4bc9f2...ee70ec )
by Alessandro
06:58
created

MongoQuerySerializer   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 1
dl 0
loc 53
ccs 0
cts 29
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 6 1
A prepareUnserializableData() 0 8 2
B prepareItemData() 0 20 6
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
    public static function serialize(Query $query)
17
    {
18
        $query->setFilters(self::prepareUnserializableData($query->getFilters()));
19
        $query->setData(self::prepareUnserializableData($query->getData()));
20
        $query->setOptions(self::prepareUnserializableData($query->getOptions()));
21
    }
22
23
    /**
24
     * @param array|object $data
25
     *
26
     * @return array|object
27
     */
28
    private static function prepareUnserializableData($data)
29
    {
30
        foreach ($data as $key => $item) {
31
            $data[$key] = self::prepareItemData($item);
32
        }
33
34
        return $data;
35
    }
36
37
    /**
38
     * @param mixed $item
39
     *
40
     * @return mixed
41
     */
42
    private static function prepareItemData($item)
43
    {
44
        if (method_exists($item, 'getArrayCopy')) {
45
            return self::prepareUnserializableData($item->getArrayCopy());
46
        }
47
48
        if (method_exists($item, 'toDateTime')) {
49
            return $item->toDateTime()->format('r');
50
        }
51
52
        if (method_exists($item, '__toString')) {
53
            return $item->__toString();
54
        }
55
56
        if (is_array($item) || is_object($item)) {
57
            return self::prepareUnserializableData((array)$item);
58
        }
59
60
        return $item;
61
    }
62
63
}
64