Passed
Push — nested-sections ( 2d40b2...7dbf34 )
by Arnaud
12:03 queued 05:37
created

MarkdownLink::process()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 23
rs 9.9
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
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
class MarkdownLink extends AbstractPostProcessor
23
{
24
    /**
25
     * {@inheritdoc}
26
     *
27
     * Replaces internal link to *.md files with the right URL.
28
     */
29
    public function process(Page $page, string $output, string $format): string
30
    {
31
        $output = preg_replace_callback(
32
            // https://regex101.com/r/ycWMe4/1
33
            '/href="(\/|)([A-Za-z0-9_\.\-\/]+)\.md(\#[A-Za-z0-9_\-]+)?"/is',
34
            function ($matches) use ($page) {
35
                // section spage
36
                $hrefPattern = 'href="../%s/%s"';
37
                // root page
38
                if (empty($page->getFolder())) {
39
                    $hrefPattern = 'href="%s/%s"';
40
                }
41
                // root link
42
                if ($matches[1] == '/') {
43
                    $hrefPattern = 'href="/%s/%s"';
44
                }
45
46
                return sprintf($hrefPattern, Page::slugify(PrefixSuffix::sub($matches[2])), $matches[3] ?? '');
47
            },
48
            $output
49
        );
50
51
        return $output;
52
    }
53
}
54