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: * Reapplies the output's original inline formatting tags
15: */
16: final class ConsoleLoopbackFormat 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: if (
43: $attributes instanceof TagAttributes
44: && $attributes->OpenTag !== null
45: && $attributes->OpenTag !== ''
46: ) {
47: $before = $attributes->OpenTag;
48: $after = $before === '<' ? '>' : $attributes->OpenTag;
49: }
50:
51: if ($before === '##') {
52: return '## ' . $text . ' ##';
53: }
54:
55: if ($this->Before === '```') {
56: return $attributes instanceof TagAttributes
57: ? $before . $attributes->InfoString . "\n"
58: . $text . "\n"
59: . $attributes->Indent . $after
60: : $before . "\n"
61: . $text . "\n"
62: . $after;
63: }
64:
65: return $before . $text . $after;
66: }
67:
68: /**
69: * @inheritDoc
70: */
71: public static function getFormatter(): Formatter
72: {
73: return new Formatter(self::getTagFormats());
74: }
75:
76: /**
77: * @inheritDoc
78: */
79: public static function getTagFormats(): TagFormats
80: {
81: return (new TagFormats(false))
82: ->withFormat(Tag::HEADING, new self('***', '***'))
83: ->withFormat(Tag::BOLD, new self('**', '**'))
84: ->withFormat(Tag::ITALIC, new self('*', '*'))
85: ->withFormat(Tag::UNDERLINE, new self('<', '>'))
86: ->withFormat(Tag::LOW_PRIORITY, new self('~~', '~~'))
87: ->withFormat(Tag::CODE_SPAN, new self('`', '`'))
88: ->withFormat(Tag::CODE_BLOCK, new self('```', '```'));
89: }
90: }
91: