|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Nip\View\Extensions\RenderConditions; |
|
6
|
|
|
|
|
7
|
|
|
use League\Plates\Engine; |
|
8
|
|
|
use Nip\View\Extensions\AbstractExtension; |
|
9
|
|
|
use Nip\View\View; |
|
10
|
|
|
use function is_callable; |
|
11
|
|
|
|
|
12
|
|
|
class RenderConditionsExtension extends AbstractExtension |
|
13
|
|
|
{ |
|
14
|
|
|
public function register(View|Engine $engine) |
|
15
|
|
|
{ |
|
16
|
|
|
parent::register($engine); |
|
17
|
|
|
$engine->addMethod('loadIfExists', [$this, 'loadIfExists']); |
|
|
|
|
|
|
18
|
|
|
$engine->addMethod('loadIf', [$this, 'loadIf']); |
|
19
|
|
|
$engine->addMethod('loadWithFallback', [$this, 'loadWithFallback']); |
|
20
|
|
|
$engine->addMethod('existPath', [$this, 'existPath']); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param array $variables |
|
25
|
|
|
* @param bool $return |
|
26
|
|
|
* |
|
27
|
|
|
* @return bool|string|void|null |
|
28
|
|
|
*/ |
|
29
|
|
|
public function loadIfExists($view, $variables = [], $return = false) |
|
30
|
|
|
{ |
|
31
|
|
|
return $this->loadIf($this->existPath($view), $view, $variables, $return); |
|
|
|
|
|
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param bool|callable $condition |
|
36
|
|
|
* @param array $variables |
|
37
|
|
|
* |
|
38
|
|
|
* @return bool|string|void|null |
|
39
|
|
|
*/ |
|
40
|
|
|
public function loadIf($condition, $view, $variables = []) |
|
41
|
|
|
{ |
|
42
|
|
|
$condition = is_callable($condition) ? $condition() : $condition; |
|
43
|
|
|
if (false == $condition) { |
|
44
|
|
|
return; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return $this->template->fetch($view, $variables); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function existPath($view): bool |
|
51
|
|
|
{ |
|
52
|
|
|
return $this->engine->existPath($view); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @param array $variables |
|
57
|
|
|
* @param bool $return |
|
58
|
|
|
* |
|
59
|
|
|
* @return bool|string|void|null |
|
60
|
|
|
*/ |
|
61
|
|
|
public function loadWithFallback($view, $fallback, $variables = [], $return = false) |
|
62
|
|
|
{ |
|
63
|
|
|
$view = $this->existPath($view) ? $view : $fallback; |
|
64
|
|
|
|
|
65
|
|
|
return $this->template->fetch($view, $variables, $return); |
|
|
|
|
|
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|