1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\Plates\Template\ResolveTemplatePath; |
4
|
|
|
|
5
|
|
|
use League\Plates\Exception\TemplateNotFound; |
6
|
|
|
use League\Plates\Template\Name; |
7
|
|
|
use League\Plates\Template\ResolveTemplatePath; |
8
|
|
|
use LogicException; |
9
|
|
|
|
10
|
|
|
/** Resolves the path from the logic in the Name class which resolves via folder lookup, and then the default directory */ |
11
|
|
|
final class NameAndFolderResolveTemplatePath implements ResolveTemplatePath |
12
|
|
|
{ |
13
|
|
|
public function __invoke(Name $name): string |
14
|
|
|
{ |
15
|
|
|
$path = $this->resolvePath($name); |
16
|
|
|
if (is_file($path)) { |
17
|
|
|
return $path; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
throw new TemplateNotFound( |
21
|
|
|
$name->getName(), |
22
|
|
|
[$path], |
23
|
|
|
'The template "'.$name->getName().'" could not be found at "'.$path.'".' |
24
|
|
|
); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function exists(Name $name): bool |
28
|
|
|
{ |
29
|
|
|
$path = $this->resolvePath($name); |
30
|
|
|
if (is_file($path)) { |
31
|
|
|
return true; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return false; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function resolvePath(Name $name): string |
38
|
|
|
{ |
39
|
|
|
$namespace = $name->getNamespace(); |
40
|
|
|
$path = $name->getPath(false); |
41
|
|
|
$defaultDirectory = $this->getDefaultDirectory($name); |
42
|
|
|
|
43
|
|
|
if (is_null($namespace)) { |
44
|
|
|
return $this->normalizePath("{$defaultDirectory}/{$path}", $name); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$folder = $name->getEngine()->getFolders()->get($namespace); |
48
|
|
|
$path = $this->normalizePath($path, $name); |
49
|
|
|
$fullPath = "{$folder->getPath()}/{$path}"; |
50
|
|
|
|
51
|
|
|
if ( |
52
|
|
|
!is_file($fullPath) |
53
|
|
|
&& $folder->getFallback() |
54
|
|
|
&& is_file("{$defaultDirectory}/{$path}") |
55
|
|
|
) { |
56
|
|
|
return "{$defaultDirectory}/{$path}"; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
|
60
|
|
|
return $fullPath; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected function normalizePath($path, Name $name): string |
64
|
|
|
{ |
65
|
|
|
if (!is_null($name->getEngine()->getFileExtension())) { |
66
|
|
|
$path .= '.'.$name->getEngine()->getFileExtension(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $path; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Get the default templates directory. |
74
|
|
|
* @return string |
75
|
|
|
*/ |
76
|
|
|
protected function getDefaultDirectory(Name $name) |
77
|
|
|
{ |
78
|
|
|
$directory = $name->getEngine()->getDirectory(); |
79
|
|
|
|
80
|
|
|
if (is_null($directory)) { |
81
|
|
|
throw new LogicException( |
82
|
|
|
'The template name "'.$name->getName().'" is not valid. '. |
83
|
|
|
'The default directory has not been defined.' |
84
|
|
|
); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $directory; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|