Passed
Pull Request — master (#1013)
by lee
07:38
created

Parser::parse()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0058

Importance

Changes 0
Metric Value
cc 4
eloc 13
c 0
b 0
f 0
nc 4
nop 0
dl 0
loc 22
ccs 13
cts 14
cp 0.9286
crap 4.0058
rs 9.8333
1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Collection\Page;
12
13
use Symfony\Component\Finder\SplFileInfo;
14
15
/**
16
 * Class Parser.
17
 */
18
class Parser
19
{
20
    // https://regex101.com/r/xH7cL3/2
21
    const PATTERN = '^\s*(?:<!--|---|\+\+\+){1}[\n\r\s]*(.*?)[\n\r\s]*(?:-->|---|\+\+\+){1}[\s\n\r]*(.*)$';
22
    /** @var SplFileInfo */
23
    protected $file;
24
    /** @var string */
25
    protected $frontmatter;
26
    /** @var string */
27
    protected $body;
28
29
    /**
30
     * @param SplFileInfo $file
31
     */
32 1
    public function __construct(SplFileInfo $file)
33
    {
34 1
        $this->file = $file;
35 1
    }
36
37
    /**
38
     * Parse the contents of the file.
39
     *
40
     * Example:
41
     * ---
42
     * title: Title
43
     * date: 2016-07-29
44
     * ---
45
     * Lorem Ipsum.
46
     *
47
     * @throws \RuntimeException
48
     *
49
     * @return self
50
     */
51 1
    public function parse(): self
52
    {
53 1
        if ($this->file->isFile()) {
54 1
            if (!$this->file->isReadable()) {
55
                throw new \RuntimeException('Cannot read file');
56
            }
57 1
            preg_match(
58 1
                '/'.self::PATTERN.'/s',
59 1
                $this->file->getContents(),
60 1
                $matches
61
            );
62
            // if there is not front matter, set body only
63 1
            if (empty($matches)) {
64 1
                $this->body = $this->file->getContents();
65
66 1
                return $this;
67
            }
68 1
            $this->frontmatter = trim($matches[1]);
69 1
            $this->body = trim($matches[2]);
70
        }
71
72 1
        return $this;
73
    }
74
75
    /**
76
     * Get frontmatter.
77
     *
78
     * @return string|null
79
     */
80 1
    public function getFrontmatter(): ?string
81
    {
82 1
        return $this->frontmatter;
83
    }
84
85
    /**
86
     * Get body.
87
     *
88
     * @return string
89
     */
90 1
    public function getBody(): string
91
    {
92 1
        return $this->body;
93
    }
94
}
95