1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Flatdown\Markdown; |
4
|
|
|
|
5
|
|
|
use 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 array |
39
|
|
|
*/ |
40
|
|
|
public $metadata; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string $filename |
44
|
|
|
*/ |
45
|
6 |
|
public function __construct($filename) |
46
|
|
|
{ |
47
|
6 |
|
$realFilename = realpath($filename); |
48
|
|
|
|
49
|
6 |
|
if (!file_exists($realFilename) || !is_readable($realFilename)) { |
50
|
3 |
|
throw new FileNotFoundException($filename); |
51
|
|
|
} |
52
|
|
|
|
53
|
3 |
|
$this->filename = $realFilename; |
54
|
3 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @return $this |
58
|
|
|
*/ |
59
|
3 |
|
public function load() |
60
|
|
|
{ |
61
|
3 |
|
$this->content = file_get_contents($this->filename); |
62
|
3 |
|
unset($this->html); |
63
|
3 |
|
unset($this->metadata); |
64
|
|
|
|
65
|
3 |
|
return $this; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param string $content_path |
70
|
|
|
* @param bool $recursive |
71
|
|
|
* @param string $base_path |
72
|
|
|
* @return array |
73
|
|
|
*/ |
74
|
3 |
|
public static function getList($content_path, $recursive = true, $base_path = '') |
75
|
|
|
{ |
76
|
3 |
|
$paths = scandir($content_path); |
77
|
3 |
|
$tree = []; |
78
|
|
|
|
79
|
3 |
|
foreach ($paths as $path) { |
80
|
3 |
|
if (in_array($path, ['.', '..'])) { |
81
|
3 |
|
continue; |
82
|
|
|
} |
83
|
3 |
|
$full_path = $content_path . DIRECTORY_SEPARATOR . $path; |
84
|
|
|
|
85
|
3 |
|
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
|
3 |
|
} elseif (preg_match('/\.md$/', $full_path)) { |
92
|
3 |
|
$route = '/' . ($base_path ? trim($base_path, '/') . '/' : ''); |
93
|
3 |
|
$tree[$path] = $route . str_replace('.md', '', urlencode($path)); |
94
|
2 |
|
} |
95
|
2 |
|
} |
96
|
|
|
|
97
|
3 |
|
return $tree; |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|