1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the ICanBoogie package. |
5
|
|
|
* |
6
|
|
|
* (c) Olivier Laviale <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace ICanBoogie\Render\TemplateResolver; |
13
|
|
|
|
14
|
|
|
use ICanBoogie\Render\TemplateResolver; |
15
|
|
|
use ICanBoogie\Render\TemplateResolverTrait; |
16
|
|
|
|
17
|
|
|
use function array_keys; |
18
|
|
|
use function array_reverse; |
19
|
|
|
use function realpath; |
20
|
|
|
|
21
|
|
|
use const DIRECTORY_SEPARATOR; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Resolves templates pathname. |
25
|
|
|
*/ |
26
|
|
|
final class Basic implements TemplateResolver |
27
|
|
|
{ |
28
|
|
|
use TemplateResolverTrait; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* An array of key/value pairs, where _key_ if a pathname and _value_ its weight. |
32
|
|
|
* |
33
|
|
|
* @var array<string, int> |
34
|
|
|
*/ |
35
|
|
|
private array $paths = []; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param string[] $paths |
39
|
|
|
*/ |
40
|
|
|
public function __construct(array $paths = []) |
41
|
|
|
{ |
42
|
|
|
foreach ($paths as $path) { |
43
|
|
|
$this->add_path($path); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @inheritdoc |
49
|
|
|
*/ |
50
|
|
|
public function resolve(string $name, array $extensions, array &$tried = []): ?string |
51
|
|
|
{ |
52
|
|
|
return $this->resolve_path($this->resolve_tries($this->get_paths(), $name, $extensions), $tried); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Adds a path to search templates in. |
57
|
|
|
* |
58
|
|
|
* Note: The path is discarded if it cannot be resolved with `realpath()`. |
59
|
|
|
* |
60
|
|
|
* @return string|false The real path, or `false` if the path was not added. |
61
|
|
|
*/ |
62
|
|
|
public function add_path(string $path, int $weight = 0): string|false |
63
|
|
|
{ |
64
|
|
|
$path = realpath($path); |
65
|
|
|
|
66
|
|
|
if (!$path) { |
67
|
|
|
return false; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$path = $path . DIRECTORY_SEPARATOR; |
71
|
|
|
$this->paths[$path] = $weight; |
72
|
|
|
|
73
|
|
|
return $path; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Returns the paths used to search templates. |
78
|
|
|
* |
79
|
|
|
* @return string[] |
80
|
|
|
*/ |
81
|
|
|
public function get_paths(): array |
82
|
|
|
{ |
83
|
|
|
return array_keys(array_reverse($this->paths)); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|