Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace Termwind\Html;
6
 
7
use Iterator;
8
use Symfony\Component\Console\Helper\Table;
9
use Symfony\Component\Console\Helper\TableCell;
10
use Symfony\Component\Console\Helper\TableCellStyle;
11
use Symfony\Component\Console\Helper\TableSeparator;
12
use Symfony\Component\Console\Output\BufferedOutput;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Termwind\Components\Element;
15
use Termwind\HtmlRenderer;
16
use Termwind\Termwind;
17
use Termwind\ValueObjects\Node;
18
use Termwind\ValueObjects\Styles;
19
 
20
/**
21
 * @internal
22
 */
23
final class TableRenderer
24
{
25
    /**
26
     * Symfony table object uses for table generation.
27
     */
28
    private Table $table;
29
 
30
    /**
31
     * This object is used for accumulating output data from Symfony table object and return it as a string.
32
     */
33
    private BufferedOutput $output;
34
 
35
    public function __construct()
36
    {
37
        $this->output = new BufferedOutput(
38
            // Content should output as is, without changes
39
            OutputInterface::VERBOSITY_NORMAL | OutputInterface::OUTPUT_RAW,
40
            true
41
        );
42
 
43
        $this->table = new Table($this->output);
44
    }
45
 
46
    /**
47
     * Converts table output to the content element.
48
     */
49
    public function toElement(Node $node): Element
50
    {
51
        $this->parseTable($node);
52
        $this->table->render();
53
 
54
        $content = preg_replace('/\n$/', '', $this->output->fetch()) ?? '';
55
 
56
        return Termwind::div($content, '', [
57
            'isFirstChild' => $node->isFirstChild(),
58
        ]);
59
    }
60
 
61
    /**
62
     * Looks for thead, tfoot, tbody, tr elements in a given DOM and appends rows from them to the Symfony table object.
63
     */
64
    private function parseTable(Node $node): void
65
    {
66
        $style = $node->getAttribute('style');
67
        if ($style !== '') {
68
            $this->table->setStyle($style);
69
        }
70
 
71
        foreach ($node->getChildNodes() as $child) {
72
            match ($child->getName()) {
73
                'thead' => $this->parseHeader($child),
74
                'tfoot' => $this->parseFoot($child),
75
                'tbody' => $this->parseBody($child),
76
                default => $this->parseRows($child)
77
            };
78
        }
79
    }
80
 
81
    /**
82
     * Looks for table header title and tr elements in a given thead DOM node and adds them to the Symfony table object.
83
     */
84
    private function parseHeader(Node $node): void
85
    {
86
        $title = $node->getAttribute('title');
87
 
88
        if ($title !== '') {
89
            $this->table->getStyle()->setHeaderTitleFormat(
90
                $this->parseTitleStyle($node)
91
            );
92
            $this->table->setHeaderTitle($title);
93
        }
94
 
95
        foreach ($node->getChildNodes() as $child) {
96
            if ($child->isName('tr')) {
97
                foreach ($this->parseRow($child) as $row) {
98
                    if (! is_array($row)) {
99
                        continue;
100
                    }
101
                    $this->table->setHeaders($row);
102
                }
103
            }
104
        }
105
    }
106
 
107
    /**
108
     * Looks for table footer and tr elements in a given tfoot DOM node and adds them to the Symfony table object.
109
     */
110
    private function parseFoot(Node $node): void
111
    {
112
        $title = $node->getAttribute('title');
113
 
114
        if ($title !== '') {
115
            $this->table->getStyle()->setFooterTitleFormat(
116
                $this->parseTitleStyle($node)
117
            );
118
            $this->table->setFooterTitle($title);
119
        }
120
 
121
        foreach ($node->getChildNodes() as $child) {
122
            if ($child->isName('tr')) {
123
                $rows = iterator_to_array($this->parseRow($child));
124
                if (count($rows) > 0) {
125
                    $this->table->addRow(new TableSeparator());
126
                    $this->table->addRows($rows);
127
                }
128
            }
129
        }
130
    }
131
 
132
    /**
133
     * Looks for tr elements in a given DOM node and adds them to the Symfony table object.
134
     */
135
    private function parseBody(Node $node): void
136
    {
137
        foreach ($node->getChildNodes() as $child) {
138
            if ($child->isName('tr')) {
139
                $this->parseRows($child);
140
            }
141
        }
142
    }
143
 
144
    /**
145
     * Parses table tr elements.
146
     */
147
    private function parseRows(Node $node): void
148
    {
149
        foreach ($this->parseRow($node) as $row) {
150
            $this->table->addRow($row);
151
        }
152
    }
153
 
154
    /**
155
     * Looks for th, td elements in a given DOM node and converts them to a table cells.
156
     *
157
     * @return Iterator<array<int, TableCell>|TableSeparator>
158
     */
159
    private function parseRow(Node $node): Iterator
160
    {
161
        $row = [];
162
 
163
        foreach ($node->getChildNodes() as $child) {
164
            if ($child->isName('th') || $child->isName('td')) {
165
                $align = $child->getAttribute('align');
166
 
167
                $class = $child->getClassAttribute();
168
 
169
                if ($child->isName('th')) {
170
                    $class .= ' strong';
171
                }
172
 
173
                $text = (string) (new HtmlRenderer)->parse(
174
                    trim(preg_replace('/<br\s?+\/?>/', "\n", $child->getHtml()) ?? '')
175
                );
176
 
177
                if ((bool) preg_match(Styles::STYLING_REGEX, $text)) {
178
                    $class .= ' font-normal';
179
                }
180
 
181
                $row[] = new TableCell(
182
                    // I need only spaces after applying margin, padding and width except tags.
183
                    // There is no place for tags, they broke cell formatting.
184
                    (string) Termwind::span($text, $class),
185
                    [
186
                        // Gets rowspan and colspan from tr and td tag attributes
187
                        'colspan' => max((int) $child->getAttribute('colspan'), 1),
188
                        'rowspan' => max((int) $child->getAttribute('rowspan'), 1),
189
 
190
                        // There are background and foreground and options
191
                        'style' => $this->parseCellStyle(
192
                            $class,
193
                            $align === '' ? TableCellStyle::DEFAULT_ALIGN : $align
194
                        ),
195
                    ]
196
                );
197
            }
198
        }
199
 
200
        if ($row !== []) {
201
            yield $row;
202
        }
203
 
204
        $border = (int) $node->getAttribute('border');
205
        for ($i = $border; $i--; $i > 0) {
206
            yield new TableSeparator();
207
        }
208
    }
209
 
210
    /**
211
     * Parses tr, td tag class attribute and passes bg, fg and options to a table cell style.
212
     */
213
    private function parseCellStyle(string $styles, string $align = TableCellStyle::DEFAULT_ALIGN): TableCellStyle
214
    {
215
        // I use this empty span for getting styles for bg, fg and options
216
        // It will be a good idea to get properties without element object and then pass them to an element object
217
        $element = Termwind::span('%s', $styles);
218
 
219
        $styles = [];
220
 
221
        $colors = $element->getProperties()['colors'] ?? [];
222
 
223
        foreach ($colors as $option => $content) {
224
            if (in_array($option, ['fg', 'bg'], true)) {
225
                $content = is_array($content) ? array_pop($content) : $content;
226
 
227
                $styles[] = "$option=$content";
228
            }
229
        }
230
 
231
        // If there are no styles we don't need extra tags
232
        if ($styles === []) {
233
            $cellFormat = '%s';
234
        } else {
235
            $cellFormat = '<'.implode(';', $styles).'>%s</>';
236
        }
237
 
238
        return new TableCellStyle([
239
            'align' => $align,
240
            'cellFormat' => $cellFormat,
241
        ]);
242
    }
243
 
244
    /**
245
     * Get styled representation of title.
246
     */
247
    private function parseTitleStyle(Node $node): string
248
    {
249
        return (string) Termwind::span(' %s ', $node->getClassAttribute());
250
    }
251
}