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
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param array $variables |
24
|
|
|
* @param bool $return |
25
|
|
|
* |
26
|
|
|
* @return bool|string|void|null |
27
|
|
|
*/ |
28
|
|
|
public function loadIfExists($view, $variables = [], $return = false) |
29
|
|
|
{ |
30
|
|
|
return $this->loadIf($this->existPath($view), $view, $variables, $return); |
|
|
|
|
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param bool|callable $condition |
35
|
|
|
* @param array $variables |
36
|
|
|
* |
37
|
|
|
* @return bool|string|void|null |
38
|
|
|
*/ |
39
|
|
|
public function loadIf($condition, $view, $variables = []) |
40
|
|
|
{ |
41
|
|
|
$condition = is_callable($condition) ? $condition() : $condition; |
42
|
|
|
if (false == $condition) { |
43
|
|
|
return; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $this->template->fetch($view, $variables); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function existPath($view): bool |
50
|
|
|
{ |
51
|
|
|
return $this->engine->existPath($view); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param array $variables |
56
|
|
|
* @param bool $return |
57
|
|
|
* |
58
|
|
|
* @return bool|string|void|null |
59
|
|
|
*/ |
60
|
|
|
public function loadWithFallback($view, $fallback, $variables = [], $return = false) |
61
|
|
|
{ |
62
|
|
|
$view = $this->existPath($view) ? $view : $fallback; |
63
|
|
|
|
64
|
|
|
return $this->template->fetch($view, $variables, $return); |
|
|
|
|
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|