1<?php
2
3namespace dokuwiki\plugin\prosemirror\parser;
4
5class TableRowNode extends Node
6{
7
8    /** @var TableCellNode[] */
9    protected $tableCells = [];
10
11    /** @var TableNode */
12    protected $parent;
13
14    public function __construct($data, Node $parent)
15    {
16        $this->parent = $parent;
17        foreach ($data['content'] as $cell) {
18            $this->tableCells[] = new TableCellNode($cell);
19        }
20    }
21
22    public function toSyntax()
23    {
24        $doc = '';
25        $rowSpans = $this->parent->getRowSpans();
26        $numColsInTable = $this->parent->getNumTableCols();
27        $lastCell = end($this->tableCells);
28        for ($colIndex = 1; $colIndex <= $numColsInTable; $colIndex += $colSpan) {
29            if (!empty($rowSpans[$colIndex])) {
30                $doc .= '| ::: ';
31                $rowSpans[$colIndex] -= 1;
32                $colSpan = 1;
33                continue;
34            }
35            $tableCell = array_shift($this->tableCells);
36            $doc .= $tableCell->toSyntax();
37
38            $rowSpan = $tableCell->getRowSpan();
39            $colSpan = $tableCell->getColSpan();
40            // does nothing if $rowSpan==1 and $colSpan==1
41            for ($colSpanIndex = 0; $colSpanIndex < $colSpan; $colSpanIndex += 1) {
42                $rowSpans[$colIndex + $colSpanIndex] = $rowSpan - 1;
43            }
44
45            $doc .= str_repeat('|', $colSpan - 1);
46
47        }
48        $this->parent->setRowSpans($rowSpans);
49
50        $postfix = $lastCell->isHeaderCell() ? '^' : '|';
51
52        return $doc . $postfix;
53    }
54
55    /**
56     * This counts the number of columns covered by the cells in the current row
57     *
58     * WARNING: This will not(!) count cells ommited due to row-spans!
59     *
60     * @return int
61     */
62    public function countCols() {
63        $cols = 0;
64        foreach ($this->tableCells as $cell) {
65            $cols += $cell->getColSpan();
66        }
67        return $cols;
68    }
69}
70