forked from paysera/lib-logging-extra-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormatterTrait.php
More file actions
97 lines (77 loc) · 2.27 KB
/
FormatterTrait.php
File metadata and controls
97 lines (77 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
declare(strict_types=1);
namespace Paysera\LoggingExtraBundle\Service\Formatter;
use DateTimeInterface;
use Doctrine\Persistence\Proxy;
use Doctrine\ORM\PersistentCollection;
use Monolog\Utils;
use Throwable;
trait FormatterTrait
{
protected function normalize(mixed $data, $depth = 0): mixed
{
$prenormalizedData = $this->preNormalizeData($data, $depth);
return parent::normalize($prenormalizedData, $depth);
}
private function preNormalizeData($data, $depth)
{
if ($depth > 2) {
return $this->getScalarRepresentation($data);
}
if ($data instanceof PersistentCollection) {
return $data->isInitialized() ? iterator_to_array($data) : get_class($data);
}
if ($data instanceof Proxy) {
return $this->normalizeProxy($data);
}
if (
is_object($data)
&& !$data instanceof DateTimeInterface
&& !$data instanceof Throwable
) {
return $this->normalizeObject($data);
}
return $data;
}
private function getScalarRepresentation(mixed $data): mixed
{
if (is_scalar($data) || $data === null) {
return $data;
}
if (is_object($data)) {
return get_class($data);
}
return gettype($data);
}
private function normalizeObject(mixed $data): array
{
$result = [];
foreach ((array)$data as $key => $value) {
$parts = explode("\0", $key);
$fixedKey = end($parts);
if (str_starts_with($fixedKey, '__')) {
continue;
}
$result[$fixedKey] = $value;
}
return $result;
}
private function normalizeProxy(Proxy $data): array|string
{
if ($data->__isInitialized()) {
return $this->normalizeObject($data);
}
if (method_exists($data, 'getId')) {
return ['id' => $data->getId()];
}
return '[Uninitialized]';
}
protected function toJson($data, $ignoreErrors = false): string
{
return Utils::jsonEncode(
$data,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
$ignoreErrors
);
}
}