FrontMatterService::_resolveTemplate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.github.com/tinydots/craft-front-matter
4
 * @copyright Copyright (c) Mike Pepper
5
 * @license MIT
6
 */
7
namespace tinydots\frontmatter\services;
8
9
use craft\base\Component;
10
use craft\web\twig\TemplateLoaderException;
11
use Mni\FrontYAML\Document;
12
use Mni\FrontYAML\Parser;
13
14
class FrontMatterService extends Component
15
{
16
    /** @var Parser The FrontYAML parser instance */
17
    protected $_parser;
18
19
    /** @var array */
20
    protected $_cache;
21
22 2
    public function init()
23
    {
24 2
        parent::init();
25
26 2
        $this->_parser = new Parser(null, null, '{#---', '---#}');
27 2
    }
28
29 2
    public function getParser()
30
    {
31 2
        return $this->_parser;
32
    }
33
34 2
    public function parseString(string $string): Document
35
    {
36 2
        $key = md5($string);
37 2
        if (!isset($this->_cache[$key])) {
38 1
            $this->_cache[$key] = $this->getParser()->parse($string, false);
39
        }
40
41 2
        return $this->_cache[$key];
42
    }
43
44
    /**
45
     * @param $templatePath
46
     * @return Document
47
     * @throws TemplateLoaderException
48
     */
49
    public function parseTemplate($templatePath): Document
50
    {
51
        $path = $this->_resolveTemplate($templatePath);
52
53
        $contents = file_get_contents($path);
54
55
        return $this->parseString($contents);
56
    }
57
58
    // Private Methods
59
    // =========================================================================
60
61
    /**
62
     * Returns the path to a given template, or throws a TemplateLoaderException.
63
     *
64
     * @param string $name
65
     * @return string
66
     * @throws TemplateLoaderException if the template doesn’t exist
67
     */
68
    private function _resolveTemplate(string $name)
69
    {
70
        $template = \Craft::$app->getView()->resolveTemplate($name);
71
72
        if ($template !== false) {
73
            return $template;
74
        }
75
76
        throw new TemplateLoaderException($name, \Craft::t('app', 'Unable to find the template “{template}”.', ['template' => $name]));
77
    }
78
}