Passed
Push — master ( aae1e6...eb8454 )
by
unknown
07:07 queued 12s
created

MarkdownLink   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 57.14%

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 30
ccs 8
cts 14
cp 0.5714
rs 10
c 0
b 0
f 0
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A process() 0 23 3
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Renderer\PostProcessor;
15
16
use Cecil\Collection\Page\Page;
17
use Cecil\Collection\Page\PrefixSuffix;
18
19
/**
20
 * MarkdownLink class.
21
 *
22
 * This class processes Markdown links in the output HTML,
23
 * replacing internal links to `.md` files with the correct URLs.
24
 * It handles links that may include a section anchor and adjusts the href attribute accordingly.
25
 */
26
class MarkdownLink extends AbstractPostProcessor
27
{
28
    /**
29
     * {@inheritdoc}
30
     *
31
     * Replaces internal link to *.md files with the right URL.
32
     */
33 1
    public function process(Page $page, string $output, string $format): string
34
    {
35 1
        $output = preg_replace_callback(
36
            // https://regex101.com/r/ycWMe4/1
37 1
            '/href="(\/|)([A-Za-z0-9_\.\-\/]+)\.md(\#[A-Za-z0-9_\-]+)?"/is',
38 1
            function ($matches) use ($page) {
39
                // section spage
40
                $hrefPattern = 'href="../%s/%s"';
41
                // root page
42
                if (empty($page->getFolder())) {
43
                    $hrefPattern = 'href="%s/%s"';
44
                }
45
                // root link
46
                if ($matches[1] == '/') {
47
                    $hrefPattern = 'href="/%s/%s"';
48
                }
49
50
                return \sprintf($hrefPattern, Page::slugify(PrefixSuffix::sub($matches[2])), $matches[3] ?? '');
51 1
            },
52 1
            $output
53 1
        );
54
55 1
        return $output;
56
    }
57
}
58