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
|
|
|
|