Template::render()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Shippinno\Template;
5
6
use League\Flysystem\Adapter\NullAdapter;
7
use League\Flysystem\FileNotFoundException;
8
use League\Flysystem\Filesystem;
9
10
abstract class Template
11
{
12
    /**
13
     * @var Filesystem
14
     */
15
    protected $filesystem;
16
17
    /**
18
     * @param Filesystem|null $filesystem
19
     */
20 9
    public function __construct(Filesystem $filesystem = null)
21
    {
22 9
        $this->filesystem = is_null($filesystem) ? new Filesystem(new NullAdapter) : $filesystem;
23 9
    }
24
25
    /**
26
     * @param string $templateName
27
     * @param array $variables
28
     * @return string
29
     * @throws LoadFailedException
30
     * @throws RenderFailedException
31
     * @throws TemplateNotFoundException
32
     */
33 5
    public function render(string $templateName, array $variables)
34
    {
35 5
        return $this->renderSource($this->readFile($templateName), $variables);
36
    }
37
38
    /**
39
     * @param string $source
40
     * @param array $variables
41
     * @return string
42
     * @throws RenderFailedException
43
     */
44
    abstract public function renderSource(string $source, array $variables): string;
45
46
    /**
47
     * @param string $templateName
48
     * @return string
49
     * @throws LoadFailedException
50
     * @throws TemplateNotFoundException
51
     */
52 5
    protected function readFile(string $templateName): string
53
    {
54 5
        $fileName = $this->fileName($templateName);
55
        try {
56 5
            $content = $this->filesystem->read($fileName);
57 2
        } catch (FileNotFoundException $e) {
58 2
            throw new TemplateNotFoundException($e->getPath());
59
        }
60 3
        if ($content === false) {
61 1
            throw new LoadFailedException($fileName);
62
        }
63
64 2
        return $content;
65
    }
66
67
    /**
68
     * @param string $templateName
69
     * @return string
70
     */
71
    abstract protected function fileName(string $templateName): string;
72
}
73