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 to console output
15: */
16: final class ConsoleMarkdownFormat 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 === '_' || $tag === '*') && (
51: !$attributes instanceof TagAttributes
52: || !$attributes->HasChildren
53: )) {
54: return '`' . Formatter::unescapeTags($text) . '`';
55: }
56:
57: if ($before === '`') {
58: return '**`' . $text . '`**';
59: }
60:
61: if ($before === '```') {
62: return $attributes instanceof TagAttributes
63: ? $tag . $attributes->InfoString . "\n"
64: . $text . "\n"
65: . $attributes->Indent . $tag
66: : $tag . "\n"
67: . $text . "\n"
68: . $tag;
69: }
70:
71: return $before . $text . $after;
72: }
73:
74: /**
75: * @inheritDoc
76: */
77: public static function getFormatter(): Formatter
78: {
79: return new Formatter(self::getTagFormats());
80: }
81:
82: /**
83: * @inheritDoc
84: */
85: public static function getTagFormats(): TagFormats
86: {
87: return (new TagFormats(false, true))
88: ->withFormat(Tag::HEADING, new self('***', '***'))
89: ->withFormat(Tag::BOLD, new self('**', '**'))
90: ->withFormat(Tag::ITALIC, new self('*', '*'))
91: ->withFormat(Tag::UNDERLINE, new self('*<u>', '</u>*'))
92: ->withFormat(Tag::LOW_PRIORITY, new self('<small>', '</small>'))
93: ->withFormat(Tag::CODE_SPAN, new self('`', '`'))
94: ->withFormat(Tag::CODE_BLOCK, new self('```', '```'));
95: }
96: }
97: