|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Service; |
|
4
|
|
|
|
|
5
|
|
|
use DOMDocument; |
|
6
|
|
|
use Knp\Bundle\MarkdownBundle\MarkdownParserInterface; |
|
7
|
|
|
use Psr\Log\LoggerInterface; |
|
8
|
|
|
use Symfony\Contracts\Cache\ItemInterface; |
|
9
|
|
|
use Symfony\Contracts\Cache\TagAwareCacheInterface; |
|
10
|
|
|
|
|
11
|
|
|
class MarkdownService |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var TagAwareCacheInterface */ |
|
14
|
|
|
private $cache; |
|
15
|
|
|
|
|
16
|
|
|
/** @var MarkdownParserInterface */ |
|
17
|
|
|
private $markdownParser; |
|
18
|
|
|
|
|
19
|
|
|
/** @var LoggerInterface */ |
|
20
|
|
|
private $logger; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct( |
|
23
|
|
|
TagAwareCacheInterface $cache, |
|
24
|
|
|
MarkdownParserInterface $markdownParserInterface, |
|
25
|
|
|
LoggerInterface $logger |
|
26
|
|
|
) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->cache = $cache; |
|
29
|
|
|
$this->markdownParser = $markdownParserInterface; |
|
30
|
|
|
$this->logger = $logger; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function markdownToText(?string $markdown): string |
|
34
|
|
|
{ |
|
35
|
|
|
if ($markdown === null || $markdown === '') { |
|
36
|
|
|
return ''; |
|
37
|
|
|
} |
|
38
|
|
|
$key = 'md_' . md5($markdown); |
|
39
|
|
|
return $this->cache->get($key, function(ItemInterface $item) use ($markdown) { |
|
40
|
|
|
$item->tag('markdown_text'); |
|
41
|
|
|
return html_entity_decode(strip_tags($this->markdownParser->transformMarkdown($markdown)), ENT_QUOTES); |
|
42
|
|
|
}); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function findLinks(?string $markdown): array |
|
46
|
|
|
{ |
|
47
|
|
|
if ($markdown === null || $markdown === '') { |
|
48
|
|
|
return []; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$results = []; |
|
52
|
|
|
$html = $this->markdownParser->transformMarkdown($markdown); |
|
53
|
|
|
$dom = new DOMDocument(); |
|
54
|
|
|
$dom->loadHTML($html); |
|
55
|
|
|
//dd($dom->saveHTML()); |
|
56
|
|
|
$links = $dom->getElementsByTagName('a'); |
|
57
|
|
|
foreach ($links as $link) { |
|
58
|
|
|
$results[] = [ |
|
59
|
|
|
'uri' => $link->getAttribute('href'), |
|
60
|
|
|
'text' => $link->textContent |
|
61
|
|
|
]; |
|
62
|
|
|
} |
|
63
|
|
|
return $results; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|