1: <?php declare(strict_types=1);
2:
3: namespace Salient\Console\Concept;
4:
5: use Salient\Contract\Console\ConsoleTag as Tag;
6: use Salient\Contract\Console\ConsoleTargetPrefixInterface;
7: use Salient\Contract\Core\MessageLevel as Level;
8:
9: /**
10: * Base class for console output targets that apply an optional prefix to each
11: * line of output
12: */
13: abstract class ConsolePrefixTarget extends ConsoleTarget implements ConsoleTargetPrefixInterface
14: {
15: private ?string $Prefix = null;
16: private int $PrefixLength = 0;
17:
18: /**
19: * @param Level::* $level
20: * @param array<string,mixed> $context
21: */
22: abstract protected function writeToTarget($level, string $message, array $context): void;
23:
24: /**
25: * @inheritDoc
26: */
27: final public function write($level, string $message, array $context = []): void
28: {
29: $this->assertIsValid();
30:
31: if ($this->Prefix === null) {
32: $this->writeToTarget($level, $message, $context);
33: return;
34: }
35:
36: $this->writeToTarget(
37: $level,
38: $this->Prefix . str_replace("\n", "\n{$this->Prefix}", $message),
39: $context
40: );
41: }
42:
43: /**
44: * @inheritDoc
45: */
46: final public function setPrefix(?string $prefix)
47: {
48: if ($prefix === null || $prefix === '') {
49: $this->Prefix = null;
50: $this->PrefixLength = 0;
51:
52: return $this;
53: }
54:
55: $this->assertIsValid();
56:
57: $this->PrefixLength = strlen($prefix);
58: $this->Prefix = $this->getFormatter()->getTagFormat(Tag::LOW_PRIORITY)->apply($prefix);
59:
60: return $this;
61: }
62:
63: /**
64: * @inheritDoc
65: */
66: final public function getPrefix(): ?string
67: {
68: $this->assertIsValid();
69:
70: return $this->Prefix;
71: }
72:
73: /**
74: * @inheritDoc
75: */
76: public function getWidth(): ?int
77: {
78: $this->assertIsValid();
79:
80: return 80 - $this->PrefixLength;
81: }
82: }
83: