X-Git-Url: https://git.immae.eu/?p=github%2Fshaarli%2FShaarli.git;a=blobdiff_plain;f=application%2Fformatter%2FParsedown%2FShaarliParsedownTrait.php;fp=application%2Fformatter%2FParsedown%2FShaarliParsedownTrait.php;h=ed7b1747453f84c4c1fd87c15eb7f19a81fa3598;hp=0000000000000000000000000000000000000000;hb=11edc143b42a7be09c0c9dc02730c83e8cbb73c2;hpb=83b4eb17958c0c03bea637db7e394f6d622aeb00 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 @@ +shaarliFormatLink(parent::inlineLink($excerpt), true); + } + + /** + * @inheritDoc + */ + protected function inlineUrl($excerpt) + { + return $this->shaarliFormatLink(parent::inlineUrl($excerpt), false); + } + + /** + * Properly format markdown link: + * - remove highlight tags from HREF attribute + * - (optional) add highlight tags to link caption + * + * @param array|null $link Parsedown formatted link array. + * It can be empty. + * @param bool $fullWrap Add highlight tags the whole link caption + * + * @return array|null + */ + protected function shaarliFormatLink(?array $link, bool $fullWrap): ?array + { + // If open and clean search tokens are found in the link, process. + if ( + is_array($link) + && strpos($link['element']['attributes']['href'] ?? '', Formatter::SEARCH_HIGHLIGHT_OPEN) !== false + && strpos($link['element']['attributes']['href'] ?? '', Formatter::SEARCH_HIGHLIGHT_CLOSE) !== false + ) { + $link['element']['attributes']['href'] = $this->shaarliRemoveSearchTokens( + $link['element']['attributes']['href'] + ); + + if ($fullWrap) { + $link['element']['text'] = Formatter::SEARCH_HIGHLIGHT_OPEN . + $link['element']['text'] . + Formatter::SEARCH_HIGHLIGHT_CLOSE + ; + } + } + + return $link; + } + + /** + * Remove open and close tags from provided string. + * + * @param string $entry input + * + * @return string Striped input + */ + protected function shaarliRemoveSearchTokens(string $entry): string + { + $entry = str_replace(Formatter::SEARCH_HIGHLIGHT_OPEN, '', $entry); + $entry = str_replace(Formatter::SEARCH_HIGHLIGHT_CLOSE, '', $entry); + + return $entry; + } +}