1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yep\WorkflowLogger\Formatter; |
4
|
|
|
|
5
|
|
|
use Yep\WorkflowLogger\ContextDumper\DumperInterface; |
6
|
|
|
use Yep\WorkflowLogger\Record; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class StandardFormatter |
10
|
|
|
* |
11
|
|
|
* @package Yep\WorkflowLogger\Formatter |
12
|
|
|
* @author Martin Zeman (Zemistr) <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class StandardFormatter implements FormatterInterface |
15
|
|
|
{ |
16
|
|
|
const FORMAT = "[%datetime%] %level%: %message%\n%contextPlaceholder%"; |
17
|
|
|
const CONTEXT_FORMAT = "Context:\n%context%\n"; |
18
|
|
|
const DATETIME_FORMAT = 'Y-m-d H:i:s.u'; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var int |
22
|
|
|
*/ |
23
|
|
|
protected $indent; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var DumperInterface |
27
|
|
|
*/ |
28
|
|
|
protected $dumper; |
29
|
|
|
|
30
|
3 |
|
public function __construct(DumperInterface $dumper, $indent = 0) |
31
|
|
|
{ |
32
|
3 |
|
$this->dumper = $dumper; |
33
|
3 |
|
$this->indent = (int)$indent; |
34
|
3 |
|
} |
35
|
|
|
|
36
|
3 |
|
protected function prepareContextPart(Record $record) |
37
|
|
|
{ |
38
|
3 |
|
$context = $record->getContext(); |
39
|
|
|
|
40
|
3 |
|
if (empty($context)) { |
41
|
1 |
|
return ''; |
42
|
|
|
} |
43
|
|
|
|
44
|
2 |
|
$dump = $this->dumper->dump($context); |
45
|
2 |
|
$dump = $this->indent($dump); |
46
|
2 |
|
$string = strtr(static::CONTEXT_FORMAT, ['%context%' => $dump]); |
47
|
2 |
|
$string = $this->indent($string); |
48
|
|
|
|
49
|
2 |
|
return $string; |
50
|
|
|
} |
51
|
|
|
|
52
|
3 |
|
public function format(Record $record) |
53
|
|
|
{ |
54
|
3 |
|
$string = strtr( |
55
|
3 |
|
static::FORMAT, |
56
|
|
|
[ |
57
|
3 |
|
'%datetime%' => $record->getDatetime()->format( |
58
|
3 |
|
static::DATETIME_FORMAT |
59
|
|
|
), |
60
|
3 |
|
'%level%' => $record->getLevel(), |
61
|
3 |
|
'%message%' => $record->getMessage(), |
62
|
3 |
|
'%contextPlaceholder%' => $this->prepareContextPart($record), |
63
|
|
|
] |
64
|
|
|
); |
65
|
|
|
|
66
|
3 |
|
$string = $this->indent($string); |
67
|
|
|
|
68
|
3 |
|
return $string; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param string $string |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
3 |
|
protected function indent($string) |
76
|
|
|
{ |
77
|
3 |
|
if ($this->indent === 0) { |
78
|
2 |
|
return $string; |
79
|
|
|
} |
80
|
|
|
|
81
|
1 |
|
return preg_replace( |
82
|
1 |
|
'#(?:^|[\r\n]+)(?=[^\r\n])#', |
83
|
1 |
|
'$0'.str_repeat(' ', $this->indent), |
84
|
1 |
|
$string |
85
|
|
|
); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|