Code Coverage |
||||||||||||||||
Lines |
Branches |
Paths |
Functions and Methods |
Classes and Traits |
||||||||||||
| Total | |
100.00% |
17 / 17 |
|
86.96% |
20 / 23 |
|
33.33% |
7 / 21 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
| TextFormatter | |
100.00% |
17 / 17 |
|
86.96% |
20 / 23 |
|
33.33% |
7 / 21 |
|
100.00% |
4 / 4 |
26.96 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| format | |
100.00% |
4 / 4 |
|
100.00% |
3 / 3 |
|
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| interpolate | |
100.00% |
8 / 8 |
|
83.33% |
10 / 12 |
|
25.00% |
3 / 12 |
|
100.00% |
1 / 1 |
6.80 | |||
| transform | |
100.00% |
4 / 4 |
|
85.71% |
6 / 7 |
|
16.67% |
1 / 6 |
|
100.00% |
1 / 1 |
4.31 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Celema\Log\Formatter; |
| 6 | |
| 7 | use Celema\Log\Formatter; |
| 8 | use Override; |
| 9 | |
| 10 | /** @api */ |
| 11 | final class TextFormatter implements Formatter |
| 12 | { |
| 13 | use PreparesValue; |
| 14 | |
| 15 | public function __construct( |
| 16 | private readonly bool $includeTraceback = true, |
| 17 | ) {} |
| 18 | |
| 19 | #[Override] |
| 20 | public function format(string $message, array $context = []): string |
| 21 | { |
| 22 | [$message, $context] = $this->interpolate($message, $context); |
| 23 | |
| 24 | if ($context === []) { |
| 25 | return $message; |
| 26 | } |
| 27 | |
| 28 | return $message . ":\n" . $this->transform($context); |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * @param array<array-key, mixed> $context |
| 33 | * @return array{string, array<array-key, mixed>} |
| 34 | */ |
| 35 | private function interpolate(string $message, array $context): array |
| 36 | { |
| 37 | $substitutes = []; |
| 38 | |
| 39 | foreach (array_keys($context) as $key) { |
| 40 | $placeholder = '{' . $key . '}'; |
| 41 | |
| 42 | if (!str_contains($message, $placeholder)) { |
| 43 | continue; |
| 44 | } |
| 45 | |
| 46 | $substitutes[$placeholder] = $this->prepare($context[$key], $this->includeTraceback); |
| 47 | unset($context[$key]); |
| 48 | } |
| 49 | |
| 50 | return [strtr($message, $substitutes), $context]; |
| 51 | } |
| 52 | |
| 53 | /** @param array<array-key, mixed> $context */ |
| 54 | private function transform(array $context): string |
| 55 | { |
| 56 | $lines = []; |
| 57 | |
| 58 | foreach (array_keys($context) as $key) { |
| 59 | $lines[] = " [{$key}] => " . $this->prepare($context[$key], $this->includeTraceback, ' '); |
| 60 | } |
| 61 | |
| 62 | return implode("\n", $lines); |
| 63 | } |
| 64 | } |