Skip to content

Commit b78e9ac

Browse files
committed
feat: can override customized functions
1 parent 178b493 commit b78e9ac

File tree

4 files changed

+37
-10
lines changed

4 files changed

+37
-10
lines changed

src/CI4Twig/Twig.php

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,16 @@ protected function addFunctions()
253253
}
254254

255255
// customized functions
256-
if (function_exists('anchor')) {
256+
$this->addCustomizedFunctions();
257+
258+
$this->functions_added = true;
259+
}
260+
261+
protected function addCustomizedFunctions()
262+
{
263+
$functions = array_merge($this->functions_asis, $this->functions_safe);
264+
265+
if (! in_array('anchor', $functions, true) && function_exists('anchor')) {
257266
$this->twig->addFunction(
258267
new TwigFunction(
259268
'anchor',
@@ -263,15 +272,15 @@ protected function addFunctions()
263272
);
264273
}
265274

266-
$this->twig->addFunction(
267-
new TwigFunction(
268-
'validation_list_errors',
269-
[$this, 'validation_list_errors'],
270-
['is_safe' => ['html']]
271-
)
272-
);
273-
274-
$this->functions_added = true;
275+
if (! in_array('validation_list_errors', $functions, true)) {
276+
$this->twig->addFunction(
277+
new TwigFunction(
278+
'validation_list_errors',
279+
[$this, 'validation_list_errors'],
280+
['is_safe' => ['html']]
281+
)
282+
);
283+
}
275284
}
276285

277286
/**

tests/CI4Twig/TwigTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,18 @@ public function testFunctionSafe()
107107
$this->assertSame("<s>test</s>\n", $output);
108108
}
109109

110+
public function testFunctionCustomized()
111+
{
112+
$obj = new Twig([
113+
'paths' => __DIR__ . '/../templates/',
114+
'functions' => ['validation_list_errors'],
115+
'cache' => false,
116+
]);
117+
118+
$output = $obj->render('functions_customized_override');
119+
$this->assertSame("override\n", $output);
120+
}
121+
110122
public function testFilter()
111123
{
112124
$obj = new Twig([
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{{ validation_list_errors() }}

tests/twig_functions.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,8 @@ function test_safe(): string
44
{
55
return '<s>test</s>';
66
}
7+
8+
function validation_list_errors(): string
9+
{
10+
return 'override';
11+
}

0 commit comments

Comments
 (0)