Completed
Push — master ( e0634d...00e983 )
by Alessandro
09:03
created

MongoLogEventSerializer::serialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
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
 */
12
class MongoLogEventSerializer
13
{
14
    /**
15
     * @param LogEvent $event
16
     */
17
    public static function serialize(LogEvent $event)
18
    {
19
        $event->setFilters(self::prepareUnserializableData($event->getFilters()));
20
        $event->setData(self::prepareUnserializableData($event->getData()));
21
        $event->setOptions(self::prepareUnserializableData($event->getOptions()));
22
    }
23
24
    /**
25
     * @param array $data
26
     *
27
     * @return array
28
     */
29
    private static function prepareUnserializableData(array $data): array
30
    {
31
        foreach ($data as $key => $item) {
32
            if (method_exists($item, 'getArrayCopy')) {
33
                $data[$key] = self::prepareUnserializableData($item->getArrayCopy());
34
            }
35
36
            if (method_exists($item, 'toDateTime')) {
37
                $data[$key] = $item->toDateTime()->format('r');
38
                continue;
39
            }
40
41
            if (method_exists($item, '__toString')) {
42
                $data[$key] = $item->__toString();
43
                continue;
44
            }
45
46
            if (is_array($item) || is_object($item)) {
47
                $data[$key] = self::prepareUnserializableData((array)$item);
48
            }
49
        }
50
51
        return $data;
52
    }
53
54
}
55