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