Completed
Push — feature-output-formats ( 710d65...5955d5 )
by Arnaud
02:00
created

Parser::getFrontmatter()   A

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