|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace League\HTMLToMarkdown\Converter; |
|
6
|
|
|
|
|
7
|
|
|
use League\HTMLToMarkdown\Configuration; |
|
8
|
|
|
use League\HTMLToMarkdown\ConfigurationAwareInterface; |
|
9
|
|
|
use League\HTMLToMarkdown\ElementInterface; |
|
10
|
|
|
|
|
11
|
|
|
class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var Configuration */ |
|
14
|
|
|
protected $config; |
|
15
|
|
|
|
|
16
|
|
|
protected function getNormTag(?ElementInterface $element): string |
|
17
|
|
|
{ |
|
18
|
|
|
if ($element !== null && ! $element->isText()) { |
|
19
|
|
|
$tag = $element->getTagName(); |
|
20
|
|
|
if ($tag === 'i' || $tag === 'em') { |
|
21
|
18 |
|
return 'em'; |
|
22
|
|
|
} |
|
23
|
18 |
|
|
|
24
|
18 |
|
if ($tag === 'b' || $tag === 'strong') { |
|
25
|
18 |
|
return 'strong'; |
|
26
|
15 |
|
} |
|
27
|
15 |
|
} |
|
28
|
12 |
|
|
|
29
|
|
|
return ''; |
|
30
|
2 |
|
} |
|
31
|
18 |
|
|
|
32
|
|
|
public function setConfig(Configuration $config): void |
|
33
|
|
|
{ |
|
34
|
|
|
$this->config = $config; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
99 |
|
public function convert(ElementInterface $element): string |
|
38
|
|
|
{ |
|
39
|
99 |
|
$tag = $this->getNormTag($element); |
|
40
|
99 |
|
$value = $element->getValue(); |
|
41
|
|
|
|
|
42
|
|
|
if (! \trim($value)) { |
|
43
|
|
|
return $value; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
if ($tag === 'em') { |
|
47
|
18 |
|
$style = $this->config->getOption('italic_style'); |
|
48
|
|
|
} else { |
|
49
|
18 |
|
$style = $this->config->getOption('bold_style'); |
|
50
|
18 |
|
} |
|
51
|
|
|
|
|
52
|
18 |
|
$prefix = \ltrim($value) !== $value ? ' ' : ''; |
|
53
|
3 |
|
$suffix = \rtrim($value) !== $value ? ' ' : ''; |
|
54
|
|
|
|
|
55
|
|
|
/* If this node is immediately preceded or followed by one of the same type don't emit |
|
56
|
18 |
|
* the start or end $style, respectively. This prevents <em>foo</em><em>bar</em> from |
|
57
|
15 |
|
* being converted to *foo**bar* which is incorrect. We want *foobar* instead. |
|
58
|
10 |
|
*/ |
|
59
|
12 |
|
$preStyle = $this->getNormTag($element->getPreviousSibling()) === $tag ? '' : $style; |
|
60
|
|
|
$postStyle = $this->getNormTag($element->getNextSibling()) === $tag ? '' : $style; |
|
61
|
|
|
|
|
62
|
18 |
|
return $prefix . $preStyle . \trim($value) . $postStyle . $suffix; |
|
63
|
18 |
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @return string[] |
|
67
|
|
|
*/ |
|
68
|
|
|
public function getSupportedTags(): array |
|
69
|
18 |
|
{ |
|
70
|
18 |
|
return ['em', 'i', 'strong', 'b']; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|