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