1: <?php declare(strict_types=1);
2:
3: namespace Salient\Console\Support;
4:
5: use Salient\Contract\Console\ConsoleFormatInterface as Format;
6: use Salient\Contract\Console\ConsoleMessageAttributesInterface as MessageAttributes;
7: use Salient\Contract\Console\ConsoleMessageFormatInterface;
8:
9: /**
10: * Applies formats to the components of a console message
11: */
12: final class ConsoleMessageFormat implements ConsoleMessageFormatInterface
13: {
14: private Format $Msg1Format;
15: private Format $Msg2Format;
16: private Format $PrefixFormat;
17: private static ConsoleMessageFormat $DefaultMessageFormat;
18:
19: public function __construct(
20: Format $msg1Format,
21: Format $msg2Format,
22: Format $prefixFormat
23: ) {
24: $this->Msg1Format = $msg1Format;
25: $this->Msg2Format = $msg2Format;
26: $this->PrefixFormat = $prefixFormat;
27: }
28:
29: /**
30: * @inheritDoc
31: */
32: public function apply(
33: string $msg1,
34: ?string $msg2,
35: string $prefix,
36: MessageAttributes $attributes
37: ): string {
38: return
39: ($prefix !== '' ? $this->PrefixFormat->apply($prefix, $attributes->withIsPrefix()) : '')
40: . ($msg1 !== '' ? $this->Msg1Format->apply($msg1, $attributes->withIsMsg1()) : '')
41: . ((string) $msg2 !== '' ? $this->Msg2Format->apply($msg2, $attributes->withIsMsg2()) : '');
42: }
43:
44: /**
45: * Get an instance that doesn't apply any formatting to messages
46: */
47: public static function getDefaultMessageFormat(): self
48: {
49: return self::$DefaultMessageFormat ??= new self(
50: ConsoleFormat::getDefaultFormat(),
51: ConsoleFormat::getDefaultFormat(),
52: ConsoleFormat::getDefaultFormat(),
53: );
54: }
55: }
56: