aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/formatter/Parsedown/ShaarliParsedownTrait.php
diff options
context:
space:
mode:
Diffstat (limited to 'application/formatter/Parsedown/ShaarliParsedownTrait.php')
-rw-r--r--application/formatter/Parsedown/ShaarliParsedownTrait.php81
1 files changed, 81 insertions, 0 deletions
diff --git a/application/formatter/Parsedown/ShaarliParsedownTrait.php b/application/formatter/Parsedown/ShaarliParsedownTrait.php
new file mode 100644
index 00000000..ed7b1747
--- /dev/null
+++ b/application/formatter/Parsedown/ShaarliParsedownTrait.php
@@ -0,0 +1,81 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Formatter\Parsedown;
6
7use Shaarli\Formatter\BookmarkDefaultFormatter as Formatter;
8
9/**
10 * Trait used for Parsedown and ParsedownExtra extension.
11 *
12 * Extended:
13 * - Format links properly in search context
14 */
15trait ShaarliParsedownTrait
16{
17 /**
18 * @inheritDoc
19 */
20 protected function inlineLink($excerpt)
21 {
22 return $this->shaarliFormatLink(parent::inlineLink($excerpt), true);
23 }
24
25 /**
26 * @inheritDoc
27 */
28 protected function inlineUrl($excerpt)
29 {
30 return $this->shaarliFormatLink(parent::inlineUrl($excerpt), false);
31 }
32
33 /**
34 * Properly format markdown link:
35 * - remove highlight tags from HREF attribute
36 * - (optional) add highlight tags to link caption
37 *
38 * @param array|null $link Parsedown formatted link array.
39 * It can be empty.
40 * @param bool $fullWrap Add highlight tags the whole link caption
41 *
42 * @return array|null
43 */
44 protected function shaarliFormatLink(?array $link, bool $fullWrap): ?array
45 {
46 // If open and clean search tokens are found in the link, process.
47 if (
48 is_array($link)
49 && strpos($link['element']['attributes']['href'] ?? '', Formatter::SEARCH_HIGHLIGHT_OPEN) !== false
50 && strpos($link['element']['attributes']['href'] ?? '', Formatter::SEARCH_HIGHLIGHT_CLOSE) !== false
51 ) {
52 $link['element']['attributes']['href'] = $this->shaarliRemoveSearchTokens(
53 $link['element']['attributes']['href']
54 );
55
56 if ($fullWrap) {
57 $link['element']['text'] = Formatter::SEARCH_HIGHLIGHT_OPEN .
58 $link['element']['text'] .
59 Formatter::SEARCH_HIGHLIGHT_CLOSE
60 ;
61 }
62 }
63
64 return $link;
65 }
66
67 /**
68 * Remove open and close tags from provided string.
69 *
70 * @param string $entry input
71 *
72 * @return string Striped input
73 */
74 protected function shaarliRemoveSearchTokens(string $entry): string
75 {
76 $entry = str_replace(Formatter::SEARCH_HIGHLIGHT_OPEN, '', $entry);
77 $entry = str_replace(Formatter::SEARCH_HIGHLIGHT_CLOSE, '', $entry);
78
79 return $entry;
80 }
81}