-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFileSystemDocumentProvider.php
More file actions
88 lines (67 loc) · 2.53 KB
/
FileSystemDocumentProvider.php
File metadata and controls
88 lines (67 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
<?php
namespace Rareloop\Primer;
use Rareloop\Primer\Contracts\DocumentParser;
use Rareloop\Primer\Contracts\DocumentProvider;
use Rareloop\Primer\Document;
use Rareloop\Primer\Exceptions\DocumentNotFoundException;
use Symfony\Component\Finder\Finder;
class FileSystemDocumentProvider implements DocumentProvider
{
protected $paths;
protected $fileExtension;
protected $documentParser;
public function __construct(array $paths, string $fileExtension, ?DocumentParser $parser = null)
{
$this->paths = $paths;
$this->fileExtension = $fileExtension;
$this->documentParser = $parser;
}
public function allDocumentIds(): array
{
if (empty($this->paths)) {
return [];
}
$finder = new Finder();
$finder->files()->in($this->paths)->name('*.' . $this->fileExtension);
return collect($finder)->map(function ($file, $test) {
return str_replace('.' . $this->fileExtension, '', $file->getRelativePathname());
})->sort()->map(function ($id) {
// Remove any numeric prefix from sub section
$id = preg_replace('/\/[0-9]+\-/', '/', $id);
// Remove any numeric prefix from top seciton
$id = preg_replace('/^[0-9]+\-/', '', $id);
return $id;
})->values()->toArray();
}
public function getDocument(string $id): Document
{
if (empty($this->paths)) {
throw new DocumentNotFoundException;
}
$finder = new Finder;
$finder->in($this->paths)->path($this->getFolderPathFromId($id));
$parts = explode('/', $id);
$filename = array_pop($parts);
$finder->name('/([0-9]+\-)?' . $filename . '\.' . $this->fileExtension . '/');
$files = array_values(iterator_to_array($finder));
if (count($files) === 0) {
throw new DocumentNotFoundException;
}
$doc = new Document($id, $files[0]->getContents());
return $this->documentParser ? $this->documentParser->parse($doc) : $doc;
}
protected function getFolderPathFromId(string $id): string
{
$parts = explode('/', $id);
array_pop($parts);
return $this->convertIdToPathRegex(implode('/', $parts));
}
protected function convertIdToPathRegex(string $id): string
{
$parts = array_map(function ($part) {
return '([0-9]+\-)?' . str_replace('-', '\-', $part);
}, explode('/', $id));
$id = '/^' . implode('\/', $parts) . '/';
return $id;
}
}