Passed
Branch master (7c3f6c)
by Javi
02:38
created

MarkdownFile::getList()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 16
nc 6
nop 3
1
<?php
2
3
namespace itsjavi\Flatdown\Markdown;
4
5
use itsjavi\Flatdown\Exceptions\FileNotFoundException;
6
7
class MarkdownFile
8
{
9
    /**
10
     * @var string
11
     */
12
    private $filename;
13
14
    /**
15
     * Raw markdown content
16
     *
17
     * @var string
18
     */
19
    public $content;
20
21
    /**
22
     * The parsed title
23
     *
24
     * @var string
25
     */
26
    public $title;
27
28
    /**
29
     * Parsed HTML content without the title
30
     *
31
     * @var string
32
     */
33
    public $html;
34
35
    /**
36
     * Parsed metadata
37
     *
38
     * @var string
39
     */
40
    public $metadata;
41
42
    /**
43
     * @param string $filename
44
     */
45
    public function __construct($filename)
46
    {
47
        $realFilename = realpath($filename);
48
49
        if (!file_exists($realFilename) || !is_readable($realFilename)) {
50
            throw new FileNotFoundException($filename);
51
        }
52
53
        $this->filename = $realFilename;
54
    }
55
56
    /**
57
     * @return $this
58
     */
59
    public function load()
60
    {
61
        $this->content = file_get_contents($this->filename);
62
        unset($this->html);
63
        unset($this->metadata);
64
65
        return $this;
66
    }
67
68
    /**
69
     * @param string $content_path
70
     * @param bool $recursive
71
     * @param string $base_path
72
     * @return array
73
     */
74
    public static function getList($content_path, $recursive = true, $base_path = '')
75
    {
76
        $paths = scandir($content_path);
77
        $tree  = [];
78
79
        foreach ($paths as $path) {
80
            if (in_array($path, ['.', '..'])) {
81
                continue;
82
            }
83
            $full_path = $content_path . DIRECTORY_SEPARATOR . $path;
84
85
            if ($recursive && is_dir($full_path) && !file_exists($full_path . '.md')) {
86
                $tree[$path] = static::getList(
87
                    $content_path . DIRECTORY_SEPARATOR . $path,
88
                    true,
89
                    rtrim($base_path, '/') . '/' . $path
90
                );
91
            } elseif (preg_match('/\.md$/', $full_path)) {
92
                $route       = '/' . ($base_path ? trim($base_path, '/') . '/' : '');
93
                $tree[$path] = $route . str_replace('.md', '', urlencode($path));
94
            }
95
        }
96
97
        return $tree;
98
    }
99
}
100