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