1: <?php declare(strict_types=1);
2:
3: namespace Salient\Console\Support;
4:
5: use Salient\Console\Contract\ConsoleFormatterFactory;
6: use Salient\Console\Contract\ConsoleTagFormatFactory;
7: use Salient\Console\Support\ConsoleTagAttributes as TagAttributes;
8: use Salient\Console\Support\ConsoleTagFormats as TagFormats;
9: use Salient\Console\ConsoleFormatter as Formatter;
10: use Salient\Contract\Console\ConsoleFormatInterface;
11: use Salient\Contract\Console\ConsoleTag as Tag;
12:
13: /**
14: * Applies Markdown formatting with man page extensions to console output
15: */
16: final class ConsoleManPageFormat implements
17: ConsoleFormatInterface,
18: ConsoleFormatterFactory,
19: ConsoleTagFormatFactory
20: {
21: private string $Before;
22: private string $After;
23:
24: public function __construct(string $before = '', string $after = '')
25: {
26: $this->Before = $before;
27: $this->After = $after;
28: }
29:
30: /**
31: * @inheritDoc
32: */
33: public function apply(?string $text, $attributes = null): string
34: {
35: if ($text === null || $text === '') {
36: return '';
37: }
38:
39: $before = $this->Before;
40: $after = $this->After;
41:
42: $tag = $attributes instanceof TagAttributes
43: ? $attributes->OpenTag
44: : '';
45:
46: if ($tag === '##') {
47: return '# ' . $text;
48: }
49:
50: if ($tag === '_') {
51: return $text;
52: }
53:
54: if ($before === '`') {
55: return '**`' . $text . '`**';
56: }
57:
58: if ($before === '```') {
59: return $attributes instanceof TagAttributes
60: ? $before . $attributes->InfoString . "\n"
61: . $text . "\n"
62: . $attributes->Indent . $after
63: : $before . "\n"
64: . $text . "\n"
65: . $after;
66: }
67:
68: return $before . $text . $after;
69: }
70:
71: /**
72: * @inheritDoc
73: */
74: public static function getFormatter(): Formatter
75: {
76: return new Formatter(self::getTagFormats());
77: }
78:
79: /**
80: * @inheritDoc
81: */
82: public static function getTagFormats(): TagFormats
83: {
84: return (new TagFormats(false, true))
85: ->withFormat(Tag::HEADING, new self('***', '***'))
86: ->withFormat(Tag::BOLD, new self('**', '**'))
87: ->withFormat(Tag::ITALIC, new self('*', '*'))
88: ->withFormat(Tag::UNDERLINE, new self('*', '*'))
89: ->withFormat(Tag::LOW_PRIORITY, new self('', ''))
90: ->withFormat(Tag::CODE_SPAN, new self('`', '`'))
91: ->withFormat(Tag::CODE_BLOCK, new self('```', '```'));
92: }
93: }
94: