FrontMatter::createJson()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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
final class FrontMatter implements FrontMatterInterface, FrontMatterExistsInterface
21
{
22
    /** @var string */
23
    private $startSep;
24
25
    /** @var string */
26
    private $endSep;
27
28
    /** @var ProcessorInterface */
29
    private $processor;
30
31
    /** @var string */
32
    private $regexp;
33
34
    public static function createYaml(): self
35
    {
36
        return new self(new YamlProcessor(), '---', '---');
37
    }
38
39
    public static function createToml(): self
40
    {
41
        return new self(new TomlProcessor(), '+++', '+++');
42
    }
43
44
    public static function createJson(): self
45
    {
46
        return new self(new JsonWithoutBracesProcessor(), '{', '}');
47
    }
48
49
    public function __construct(ProcessorInterface $processor = null, string $startSep = '---', string $endSep = '---')
50
    {
51
        $this->startSep = $startSep;
52
        $this->endSep = $endSep;
53
        $this->processor = $processor ?: new YamlProcessor();
54
55
        $this->regexp = '{^(?:'.preg_quote($startSep).")[\r\n|\n]*(.*?)[\r\n|\n]+(?:".preg_quote($endSep).")[\r\n|\n]*(.*)$}s";
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function parse(string $source): Document
62
    {
63
        if (preg_match($this->regexp, $source, $matches) === 1) {
64
            /** @var array<string, mixed> $data */
65
            $data = '' !== trim($matches[1]) ? $this->processor->parse(trim($matches[1])) : [];
66
67
            return new Document($matches[2], $data);
68
        }
69
70
        return new Document($source);
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function dump(Document $document): string
77
    {
78
        $data = trim($this->processor->dump($document->getData()));
79
        if ('' === $data) {
80
            return $document->getContent();
81
        }
82
83
        return sprintf("%s\n%s\n%s\n%s", $this->startSep, $data, $this->endSep, $document->getContent());
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function exists(string $source): bool
90
    {
91
        return preg_match($this->regexp, $source) === 1;
92
    }
93
}
94