Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
PadColonColumnsLogProcessor
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 2
12
0.00% covered (danger)
0.00%
0 / 1
 __invoke
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 pad
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Attempt to align text following `:` in a log message.
4 *
5 * But use `:::` to indicate it should be padded.
6 *
7 * @package brianhenryie/strauss
8 */
9
10namespace BrianHenryIE\Strauss\Helpers\Log;
11
12use DateTimeInterface;
13use Monolog\Processor\ProcessorInterface;
14
15/**
16 * @phpstan-type MonologRecordArray array{message: string, context: array<string,mixed>, level: 100|200|250|300|400|500|550|600, level_name: 'ALERT'|'CRITICAL'|'DEBUG'|'EMERGENCY'|'ERROR'|'INFO'|'NOTICE'|'WARNING', channel: string, datetime: DateTimeInterface, extra: array<mixed>}
17 */
18class PadColonColumnsLogProcessor implements ProcessorInterface
19{
20    /** @var int $padLength */
21    protected int $padLength = 0;
22
23    /**
24     * @param MonologRecordArray $record
25     * @return MonologRecordArray
26     */
27    public function __invoke(array $record): array
28    {
29        $message = $record['message'];
30
31        $messageParts = explode(':::', $message, 2);
32
33        /**
34         * @see https://github.com/BrianHenryIE/strauss/pull/231#pullrequestreview-3600736232
35         */
36        if (count($messageParts) < 2) {
37            return $record;
38        }
39
40        $this->padLength = max($this->padLength, strlen($messageParts[0]) + 1);
41
42        $messageParts[0] = $this->pad($messageParts[0], $this->padLength);
43
44        $record['message'] = implode('', $messageParts);
45
46        return $record;
47    }
48
49    private function pad(string $text, int $padLength): string
50    {
51        $padded = str_pad($text, $padLength, ' ', STR_PAD_RIGHT);
52        return str_replace($text, $text . ':', $padded);
53    }
54}