TemplateFormatter   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 39
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A format() 0 7 2
A interpolate() 0 22 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Conia\Log\Formatter;
6
7
use Conia\Log\Formatter;
8
9
/** @psalm-api */
10
class TemplateFormatter implements Formatter
11
{
12
    use PreparesValue;
13
14 4
    public function __construct(protected readonly bool $includeTraceback = true)
15
    {
16 4
    }
17
18 4
    public function format(string $message, ?array $context): string
19
    {
20 4
        if ($context) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $context of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
21 4
            return $this->interpolate($message, $context);
22
        }
23
24 1
        return $message;
25
    }
26
27 4
    protected function interpolate(string $template, array $context): string
28
    {
29 4
        $substitutes = [];
30
31
        /**
32
         * @psalm-suppress MixedAssignment
33
         *
34
         * $value types are exhaustively checked
35
         */
36 4
        foreach ($context as $key => $value) {
37 4
            $placeholder = '{' . $key . '}';
38
39 4
            if (strpos($template, $placeholder) === false) {
40 1
                continue;
41
            }
42
43 4
            $substitutes[$placeholder] = $this->prepare($value, $this->includeTraceback);
44
        }
45
46 4
        $message = strtr($template, $substitutes);
47
48 4
        return $message;
49
    }
50
}
51