]>
Commit | Line | Data |
---|---|---|
9ef8555a A |
1 | <?php |
2 | ||
3 | declare(strict_types=1); | |
4 | ||
5 | namespace Shaarli\Formatter\Parsedown; | |
6 | ||
7 | use Shaarli\Formatter\BookmarkDefaultFormatter as Formatter; | |
8 | ||
a1cd7a3b A |
9 | /** |
10 | * Trait used for Parsedown and ParsedownExtra extension. | |
11 | * | |
12 | * Extended: | |
13 | * - Format links properly in search context | |
14 | */ | |
9ef8555a A |
15 | trait ShaarliParsedownTrait |
16 | { | |
a1cd7a3b A |
17 | /** |
18 | * @inheritDoc | |
19 | */ | |
9ef8555a A |
20 | protected function inlineLink($excerpt) |
21 | { | |
22 | return $this->shaarliFormatLink(parent::inlineLink($excerpt), true); | |
23 | } | |
24 | ||
a1cd7a3b A |
25 | /** |
26 | * @inheritDoc | |
27 | */ | |
9ef8555a A |
28 | protected function inlineUrl($excerpt) |
29 | { | |
30 | return $this->shaarliFormatLink(parent::inlineUrl($excerpt), false); | |
31 | } | |
32 | ||
a1cd7a3b A |
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 | */ | |
9ef8555a A |
44 | protected function shaarliFormatLink(?array $link, bool $fullWrap): ?array |
45 | { | |
a1cd7a3b | 46 | // If open and clean search tokens are found in the link, process. |
9ef8555a A |
47 | if ( |
48 | is_array($link) | |
a1cd7a3b A |
49 | && strpos($link['element']['attributes']['href'] ?? '', Formatter::SEARCH_HIGHLIGHT_OPEN) !== false |
50 | && strpos($link['element']['attributes']['href'] ?? '', Formatter::SEARCH_HIGHLIGHT_CLOSE) !== false | |
9ef8555a A |
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 | ||
a1cd7a3b A |
67 | /** |
68 | * Remove open and close tags from provided string. | |
69 | * | |
70 | * @param string $entry input | |
71 | * | |
72 | * @return string Striped input | |
73 | */ | |
9ef8555a A |
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 | } |