Parser::parse()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Flaviozantut;
4
5
use Config;
6
use Exception;
7
use Parsedown;
8
use Symfony\Component\Yaml\Yaml;
9
10
class Parser
11
{
12
    private $parser;
13
14
    private $delimiter;
15
16 13
    public function __construct($strToParse = null)
17
    {
18 13
        $this->parser = new Parsedown();
19 13
        $this->delimiter = Config::get('skorry.metadata_delimiter');
20 13
        if ($strToParse) {
21 2
            $this->parse($strToParse);
22 1
        }
23 12
    }
24
25 3
    public function delimiter()
26
    {
27 3
        return $this->delimiter;
28
    }
29
30 5
    public function parse($strToParse)
31
    {
32 5
        $this->metadata = $this->extactMetadata($strToParse);
33 4
        $this->content = $this->extactContent($strToParse);
34
35 4
        return $this;
36
    }
37
38 5
    public function metadata($key = null)
39
    {
40 5
        if ($key) {
41 4
            return $this->metadata[$key];
42
        }
43
44 1
        return $this->metadata;
45
    }
46
47 4
    public function content()
48
    {
49 4
        return $this->content;
50
    }
51
52 5
    private function extactMetadata($str)
53
    {
54 5
        preg_match("/^{$this->delimiter}\n(.*)\n{$this->delimiter}\n/s", $str, $match);
55 5
        if (!isset($match[1])) {
56 1
            throw new Exception('Metadata not defined');
57 1
        }
58
59 4
        return Yaml::parse($match[1]);
60
    }
61
62 4
    private function extactContent($str)
63
    {
64 4
        $md = preg_replace("/^{$this->delimiter}(.*){$this->delimiter}\n/s", '', $str);
65
66 4
        return $this->parser->parse($md);
67
    }
68
}
69