Completed
Push — master ( 1bdfd0...0f65c5 )
by Alessandro
07:54 queued 05:07
created

MongoLogEventSerializer::prepareItemData()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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