TemplateFormatter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
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