|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This is part of the webuni/front-matter package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Martin Hasoň <[email protected]> |
|
7
|
|
|
* (c) Webuni s.r.o. <[email protected]> |
|
8
|
|
|
* |
|
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
10
|
|
|
* file that was distributed with this source code. |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace Webuni\FrontMatter; |
|
14
|
|
|
|
|
15
|
|
|
use Webuni\FrontMatter\Processor\JsonWithoutBracesProcessor; |
|
16
|
|
|
use Webuni\FrontMatter\Processor\ProcessorInterface; |
|
17
|
|
|
use Webuni\FrontMatter\Processor\TomlProcessor; |
|
18
|
|
|
use Webuni\FrontMatter\Processor\YamlProcessor; |
|
19
|
|
|
|
|
20
|
|
|
class FrontMatter implements FrontMatterInterface |
|
21
|
|
|
{ |
|
22
|
|
|
private $startSep; |
|
23
|
|
|
private $endSep; |
|
24
|
|
|
private $processor; |
|
25
|
|
|
private $regexp; |
|
26
|
|
|
|
|
27
|
|
|
public static function createYaml() |
|
28
|
|
|
{ |
|
29
|
|
|
return new static(new YamlProcessor(), '---', '---'); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public static function createToml() |
|
33
|
|
|
{ |
|
34
|
|
|
return new static(new TomlProcessor(), '+++', '+++'); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public static function createJson() |
|
38
|
|
|
{ |
|
39
|
|
|
return new static(new JsonWithoutBracesProcessor(), '{', '}'); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public function __construct(ProcessorInterface $processor = null, $startSep = '---', $endSep = '---') |
|
43
|
|
|
{ |
|
44
|
|
|
$this->startSep = $startSep; |
|
45
|
|
|
$this->endSep = $endSep; |
|
46
|
|
|
$this->processor = $processor ?: new YamlProcessor(); |
|
47
|
|
|
|
|
48
|
|
|
$this->regexp = '{^(?:'.preg_quote($startSep).")[\r\n|\n]*(.*?)[\r\n|\n]+(?:".preg_quote($endSep).")[\r\n|\n]*(.*)$}s"; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* {@inheritdoc} |
|
53
|
|
|
*/ |
|
54
|
|
|
public function parse($source) |
|
55
|
|
|
{ |
|
56
|
|
|
if (preg_match($this->regexp, $source, $matches) === 1) { |
|
57
|
|
|
$data = '' !== trim($matches[1]) ? $this->processor->parse(trim($matches[1])) : []; |
|
58
|
|
|
|
|
59
|
|
|
return new Document($matches[2], $data); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return new Document($source); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* {@inheritdoc} |
|
67
|
|
|
*/ |
|
68
|
|
|
public function dump(Document $document) |
|
69
|
|
|
{ |
|
70
|
|
|
$data = trim($this->processor->dump($document->getData())); |
|
71
|
|
|
if ('' === $data) { |
|
72
|
|
|
return $document->getContent(); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
return sprintf("%s\n%s\n%s\n%s", $this->startSep, $data, $this->endSep, $document->getContent()); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
public function hasFrontMatter(string $source): bool |
|
79
|
|
|
{ |
|
80
|
|
|
return preg_match($this->regexp, $source) === 1; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|