Completed
Pull Request — master (#18)
by Alessandro
04:04 queued 01:34
created

MongoLogEventSerializer::prepareItemData()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6.288

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
ccs 8
cts 10
cp 0.8
rs 8.8571
cc 6
eloc 10
nc 5
nop 1
crap 6.288
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 1
    public static function serialize(LogEvent $event)
18
    {
19 1
        $event->setFilters(self::prepareUnserializableData($event->getFilters()));
20 1
        $event->setData(self::prepareUnserializableData($event->getData()));
21 1
        $event->setOptions(self::prepareUnserializableData($event->getOptions()));
22 1
    }
23
24
    /**
25
     * @param array|object $data
26
     *
27
     * @return array|object
28
     */
29 1
    private static function prepareUnserializableData($data)
30
    {
31 1
        foreach ($data as $key => $item) {
32 1
            $data[$key] = self::prepareItemData($item);
33
        }
34
35 1
        return $data;
36
    }
37
38
    /**
39
     * @param mixed $item
40
     *
41
     * @return mixed
42
     */
43 1
    private static function prepareItemData($item)
44
    {
45 1
        if (method_exists($item, 'getArrayCopy')) {
46 1
            return self::prepareUnserializableData($item->getArrayCopy());
47
        }
48
49 1
        if (method_exists($item, 'toDateTime')) {
50 1
            return $item->toDateTime()->format('r');
51
        }
52
53 1
        if (method_exists($item, '__toString')) {
54
            return $item->__toString();
55
        }
56
57 1
        if (is_array($item) || is_object($item)) {
58
            return self::prepareUnserializableData((array)$item);
59
        }
60
61 1
        return $item;
62
    }
63
64
}
65