1: <?php declare(strict_types=1);
2:
3: namespace Salient\Console\Support;
4:
5: use Salient\Console\Support\ConsoleMessageFormat as MessageFormat;
6: use Salient\Contract\Console\ConsoleInterface as Console;
7:
8: /**
9: * Maps message levels and types to formats
10: *
11: * If multiple formats are assigned to the same level and type, the format
12: * assigned last takes precedence.
13: */
14: final class ConsoleMessageFormats
15: {
16: /** @var array<Console::LEVEL_*,array<Console::TYPE_*,MessageFormat>> */
17: private array $Formats = [];
18: private MessageFormat $FallbackFormat;
19:
20: public function __construct(?MessageFormat $fallbackFormat = null)
21: {
22: $this->FallbackFormat = $fallbackFormat
23: ?: MessageFormat::getDefaultMessageFormat();
24: }
25:
26: /**
27: * Assign a format to one or more message levels and types
28: *
29: * @param array<Console::LEVEL_*>|Console::LEVEL_* $level
30: * @param array<Console::TYPE_*>|Console::TYPE_* $type
31: * @return $this
32: */
33: public function set($level, $type, MessageFormat $format)
34: {
35: foreach ((array) $level as $level) {
36: foreach ((array) $type as $_type) {
37: $this->Formats[$level][$_type] = $format;
38: }
39: }
40:
41: return $this;
42: }
43:
44: /**
45: * Get the format assigned to a message level and type
46: *
47: * @param Console::LEVEL_* $level
48: * @param Console::TYPE_* $type
49: */
50: public function get(int $level, $type): MessageFormat
51: {
52: return $this->Formats[$level][$type] ?? $this->FallbackFormat;
53: }
54: }
55: