-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathBlogRepository.php
More file actions
95 lines (74 loc) · 2.53 KB
/
Copy pathBlogRepository.php
File metadata and controls
95 lines (74 loc) · 2.53 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace App\Web\Blog;
use DateTimeImmutable;
use Exception;
use League\CommonMark\Extension\FrontMatter\Output\RenderedContentWithFrontMatter;
use League\CommonMark\MarkdownConverter;
use Spatie\YamlFrontMatter\YamlFrontMatter;
use Tempest\Support\Arr\ImmutableArray;
use function Tempest\map;
use function Tempest\Support\arr;
final readonly class BlogRepository
{
public function __construct(
private MarkdownConverter $markdown,
) {
}
/**
* @return ImmutableArray<\App\Web\Blog\BlogPost>
*/
public function all(bool $loadContent = false): ImmutableArray
{
return arr(glob(__DIR__ . '/articles/*.md'))
->reverse()
->map(function (string $path) use ($loadContent) {
preg_match('/\d+-\d+-\d+-(?<slug>.*)\.md/', $path, $matches);
$data = [
'slug' => $matches['slug'],
'createdAt' => $this->parseDate($path),
'tag' => null,
'description' => null,
...YamlFrontMatter::parse(file_get_contents($path))->matter(),
];
if ($loadContent) {
$data['content'] = $this->parseContent($path)->getContent();
}
return $data;
})
->mapTo(BlogPost::class)
->filter(fn (BlogPost $post) => $post->published);
}
public function find(string $slug): ?BlogPost
{
$path = glob(__DIR__ . "/articles/*{$slug}*.md")[0] ?? null;
if (! $path) {
return null;
}
$content = $this->parseContent($path);
$data = [
'slug' => $slug,
'content' => $content->getContent(),
'createdAt' => $this->parseDate($path),
...$content->getFrontMatter(),
];
return map($data)->to(BlogPost::class);
}
private function parseContent(string $path): ?RenderedContentWithFrontMatter
{
$content = @file_get_contents($path);
if (! $content) {
return null;
}
$parsed = $this->markdown->convert($content);
if (! ($parsed instanceof RenderedContentWithFrontMatter)) {
throw new Exception("Missing frontmatter or content in {$path}");
}
return $parsed;
}
private function parseDate(string $path): DateTimeImmutable
{
preg_match('#\d+-\d+-\d+#', $path, $matches);
$date = $matches[0] ?? null;
return new DateTimeImmutable($date ?? 'now');
}
}