AbstractHeaderFormatter   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 16
dl 0
loc 33
rs 10
c 1
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A format() 0 26 5
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 *  This file is part of the Micro framework package.
7
 *
8
 *  (c) Stanislau Komar <[email protected]>
9
 *
10
 *  For the full copyright and license information, please view the LICENSE
11
 *  file that was distributed with this source code.
12
 */
13
14
namespace Micro\Plugin\Http\Business\Logger\Formatter\Format;
15
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
19
/**
20
 * @author Stanislau Komar <[email protected]>
21
 *
22
 * @codeCoverageIgnore
23
 */
24
abstract class AbstractHeaderFormatter implements LogFormatterConcreteInterface
25
{
26
    public function format(Request $request, ?Response $response, ?\Throwable $exception, ?string $message = null): string
27
    {
28
        if (!$message) {
29
            return '';
30
        }
31
32
        $matchPattern = sprintf('/{{%s_header\.(.*?)}}/', $this->getPrefix());
33
        $matched = preg_match_all($matchPattern, $message, $matches);
34
        if (!$matched || 2 !== \count($matches)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matched of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
35
            return $message;
36
        }
37
38
        $matchesPattern = $matches[0];
39
        $matchesVars = $matches[1];
40
41
        $countMatches = \count($matchesVars);
42
43
        for ($i = 0; $i < $countMatches; ++$i) {
44
            $message = str_ireplace(
45
                $matchesPattern[$i],
46
                $this->getValue($request, $response, $matchesVars[$i]),
47
                $message
48
            );
49
        }
50
51
        return $message;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $message could return the type array which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
52
    }
53
54
    abstract protected function getValue(Request $request, ?Response $response, string $matchedVar): string;
55
56
    abstract protected function getPrefix(): string;
57
}
58