TableSyncFormatter::wrapAttributes()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Umbrellio\TableSync\Monolog\Formatter;
6
7
use Monolog\Formatter\NormalizerFormatter;
8
9
class TableSyncFormatter extends NormalizerFormatter
10
{
11 3
    public function format(array $record)
12
    {
13 3
        return [
14 3
            'datetime' => (string) $record['datetime'],
15 3
            'message' => $record['message'],
16 3
            'direction' => $this->getDirection($record),
17 3
            'routing' => $this->getRoutingKey($record),
18 3
            'model' => $this->getModel($record),
19 3
            'event' => $this->getEventType($record),
20 3
            'attributes' => $this->getAttributes($record),
21 3
            'exception' => $record['context']['exception'] ?? null,
22 3
        ];
23
    }
24
25 4
    protected function getDirection(array $record): string
26
    {
27 4
        return $record['context']['direction'] ?? '';
28
    }
29
30 3
    protected function getRoutingKey(array $record): string
31
    {
32 3
        return $record['context']['routing_key'] ?? '';
33
    }
34
35 4
    protected function getEventType(array $record): string
36
    {
37 4
        return $this->getBody($record)['event'] ?? '';
38
    }
39
40 4
    protected function getModel(array $record): string
41
    {
42 4
        return $this->getBody($record)['model'] ?? '';
43
    }
44
45 4
    protected function getAttributes(array $record): array
46
    {
47 4
        if (!$body = $this->getBody($record)) {
48 1
            return [];
49
        }
50
51 4
        $attributes = $this->wrapAttributes($body['attributes']);
52
53 4
        return $this->addVersions($attributes, $body['version']);
54
    }
55
56 4
    protected function getBody(array $record): array
57
    {
58 4
        return (array) json_decode($record['context']['body'] ?? '', true);
59
    }
60
61 4
    private function wrapAttributes(array $attributes): array
62
    {
63 4
        $keys = array_keys($attributes);
64
65 4
        $isArray = collect($keys)
66 4
            ->every(function ($key) {
67 4
                return is_numeric($key);
68 4
            });
69
70 4
        return $isArray ? $attributes : [$attributes];
71
    }
72
73 4
    private function addVersions(array $items, float $version): array
74
    {
75 4
        return array_map(function ($item) use ($version) {
76 4
            return array_merge($item, compact('version'));
77 4
        }, $items);
78
    }
79
}
80