aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/formatter/Parsedown/ShaarliParsedownTrait.php
blob: e6f4dabb8ae8d751947e3d1d5a4f55213cbcdfc2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php

declare(strict_types=1);

namespace Shaarli\Formatter\Parsedown;

use Shaarli\Formatter\BookmarkDefaultFormatter as Formatter;

trait ShaarliParsedownTrait
{
    protected function inlineLink($excerpt)
    {
        return $this->shaarliFormatLink(parent::inlineLink($excerpt), true);
    }

    protected function inlineUrl($excerpt)
    {
        return $this->shaarliFormatLink(parent::inlineUrl($excerpt), false);
    }

    protected function shaarliFormatLink(?array $link, bool $fullWrap): ?array
    {
        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;
    }

    protected function shaarliRemoveSearchTokens(string $entry): string
    {
        $entry = str_replace(Formatter::SEARCH_HIGHLIGHT_OPEN, '', $entry);
        $entry = str_replace(Formatter::SEARCH_HIGHLIGHT_CLOSE, '', $entry);

        return $entry;
    }
}