1<?php
2
3namespace dokuwiki\plugin\prosemirror\parser;
4
5class TableCellNode extends Node
6{
7
8    protected $data;
9
10    /** @var Node[] */
11    protected $subnodes;
12
13    public function __construct($data, Node $parent = null)
14    {
15        if (empty($data['content'])) {
16            $data['content'] = [
17                [
18                    'type' => 'text',
19                    'text' => ' ',
20                ]
21            ];
22        }
23        $this->data = $data;
24
25        $previousNode = null;
26        foreach ($data['content'] as $nodeData) {
27            try {
28                $newNode = static::getSubNode($nodeData, $this, $previousNode);
29            } catch (\Throwable $e) {
30                var_dump($nodeData);
31                throw $e;
32            }
33            $this->subnodes[] = $newNode;
34            $previousNode = $newNode;
35        }
36    }
37
38    public function toSyntax()
39    {
40        $prefix = '|';
41        if ($this->isHeaderCell()) {
42            $prefix = '^';
43        }
44        $doc = '';
45        foreach ($this->subnodes as $subnode) {
46            $doc .= $subnode->toSyntax();
47        }
48        list($paddingLeft, $paddingRight) = $this->calculateAlignmentPadding();
49        return $prefix . $paddingLeft . trim($doc) . $paddingRight;
50    }
51
52    public function isHeaderCell()
53    {
54        return $this->data['type'] === 'table_header';
55    }
56
57    public function getRowSpan()
58    {
59        return $this->data['attrs']['rowspan'];
60    }
61
62    public function getColSpan()
63    {
64        return $this->data['attrs']['colspan'];
65    }
66
67    /**
68     * Calculate the correct padding to align cell-content left, right or center
69     *
70     * @return String[] [left padding, right padding]
71     */
72    protected function calculateAlignmentPadding()
73    {
74        if ($this->data['attrs']['align'] === 'right') {
75            return ['  ', ' '];
76        }
77        if ($this->data['attrs']['align'] === 'center') {
78            return ['  ', '  '];
79        }
80        if ($this->data['attrs']['align'] === 'left') {
81            return [' ', '  '];
82        }
83        return [' ', ' '];
84
85    }
86}
87