1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chinstrap\Core\Sources; |
6
|
|
|
|
7
|
|
|
use Chinstrap\Core\Contracts\Objects\Document; |
8
|
|
|
use Chinstrap\Core\Contracts\Sources\Source; |
9
|
|
|
use Chinstrap\Core\Objects\MarkdownDocument; |
10
|
|
|
use DateTime; |
11
|
|
|
use League\Flysystem\FilesystemInterface; |
12
|
|
|
use Mni\FrontYAML\Document as ParsedDocument; |
13
|
|
|
use Mni\FrontYAML\Parser; |
14
|
|
|
use PublishingKit\Utilities\Collections\LazyCollection; |
15
|
|
|
use PublishingKit\Utilities\Contracts\Collectable; |
16
|
|
|
|
17
|
|
|
final class MarkdownFiles implements Source |
18
|
|
|
{ |
19
|
|
|
protected FilesystemInterface $fs; |
20
|
|
|
|
21
|
|
|
protected Parser $parser; |
22
|
|
|
|
23
|
|
|
public function __construct(FilesystemInterface $fs, Parser $parser) |
24
|
|
|
{ |
25
|
|
|
$this->fs = $fs; |
26
|
|
|
$this->parser = $parser; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function all(): Collectable |
30
|
|
|
{ |
31
|
|
|
return LazyCollection::make(function () { |
32
|
|
|
/** @var array<array{type: string, path: string}> $files **/ |
33
|
|
|
$files = $this->fs->listContents('content://', true); |
34
|
|
|
foreach ($files as $file) { |
35
|
|
|
if ($file['type'] === 'dir') { |
36
|
|
|
continue; |
37
|
|
|
} |
38
|
|
|
if (!preg_match('/.(markdown|md)$/', $file['path'])) { |
39
|
|
|
continue; |
40
|
|
|
} |
41
|
|
|
if (!$content = $this->fs->read('content://' . $file['path'])) { |
42
|
|
|
continue; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
yield $this->fromMarkdown($this->parser->parse($content), $file['path']); |
46
|
|
|
} |
47
|
|
|
}); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function find(string $name): ?Document |
51
|
|
|
{ |
52
|
|
|
// Does that page exist? |
53
|
|
|
$path = rtrim($name, '/') . '.md'; |
54
|
|
|
if (!$this->fs->has("content://" . $path)) { |
55
|
|
|
return null; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// Get content |
59
|
|
|
if (!$rawcontent = $this->fs->read("content://" . $path)) { |
60
|
|
|
return null; |
61
|
|
|
} |
62
|
|
|
return $this->fromMarkdown($this->parser->parse($rawcontent), $path); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private function fromMarkdown(ParsedDocument $doc, string $path): MarkdownDocument |
66
|
|
|
{ |
67
|
|
|
$document = new MarkdownDocument(); |
68
|
|
|
$document->setContent($doc->getContent()); |
69
|
|
|
/** @var string $field **/ |
70
|
|
|
/** @var string|array $value **/ |
71
|
|
|
foreach ($doc->getYAML() as $field => $value) { |
72
|
|
|
assert(is_string($field)); |
73
|
|
|
$document->setField($field, $value); |
74
|
|
|
} |
75
|
|
|
$document->setPath($path); |
76
|
|
|
$lastUpdated = new DateTime(); |
77
|
|
|
if ($timestamp = $this->fs->getTimestamp("content://" . $path)) { |
78
|
|
|
$lastUpdated->setTimestamp($timestamp); |
79
|
|
|
} |
80
|
|
|
$document->setUpdatedAt($lastUpdated); |
81
|
|
|
return $document; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|