1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
<?php
declare(strict_types=1);
namespace League\HTMLToMarkdown\Converter;
use League\HTMLToMarkdown\Coerce;
use League\HTMLToMarkdown\Configuration;
use League\HTMLToMarkdown\ConfigurationAwareInterface;
use League\HTMLToMarkdown\ElementInterface;
use League\HTMLToMarkdown\PreConverterInterface;
class TableConverter implements ConverterInterface, PreConverterInterface, ConfigurationAwareInterface
{
/** @var Configuration */
protected $config;
public function setConfig(Configuration $config): void
{
$this->config = $config;
}
/** @var array<string, string> */
private static $alignments = [
'left' => ':--',
'right' => '--:',
'center' => ':-:',
];
/** @var array<int, string>|null */
private $columnAlignments = [];
/** @var string|null */
private $caption = null;
public function preConvert(ElementInterface $element): void
{
$tag = $element->getTagName();
// Only table cells and caption are allowed to contain content.
// Remove all text between other table elements.
if ($tag === 'th' || $tag === 'td' || $tag === 'caption') {
return;
}
foreach ($element->getChildren() as $child) {
if ($child->isText()) {
$child->setFinalMarkdown('');
}
}
}
public function convert(ElementInterface $element): string
{
$value = $element->getValue();
switch ($element->getTagName()) {
case 'table':
$this->columnAlignments = [];
if ($this->caption) {
$side = $this->config->getOption('table_caption_side');
if ($side === 'top') {
$value = $this->caption . "\n" . $value;
} elseif ($side === 'bottom') {
$value .= $this->caption;
}
$this->caption = null;
}
return $value . "\n";
case 'caption':
$this->caption = \trim($value);
return '';
case 'tr':
$value .= "|\n";
if ($this->columnAlignments !== null) {
$value .= '|' . \implode('|', $this->columnAlignments) . "|\n";
$this->columnAlignments = null;
}
return $value;
case 'th':
case 'td':
if ($this->columnAlignments !== null) {
$align = $element->getAttribute('align');
$this->columnAlignments[] = self::$alignments[$align] ?? '---';
}
$value = \str_replace("\n", ' ', $value);
$value = \str_replace('|', Coerce::toString($this->config->getOption('table_pipe_escape') ?? '\|'), $value);
return '| ' . \trim($value) . ' ';
case 'thead':
case 'tbody':
case 'tfoot':
case 'colgroup':
case 'col':
return $value;
default:
return '';
}
}
/**
* @return string[]
*/
public function getSupportedTags(): array
{
return ['table', 'tr', 'th', 'td', 'thead', 'tbody', 'tfoot', 'colgroup', 'col', 'caption'];
}
}
|