Skip to content

Commit ba9a2b4

Browse files
committed
Inspect constant() tests (not just function calls)
I was unaware the AST represents `is constant()` differently from `== constant()`. Therefore, `{{ 'foo' is constant('FOO') }}` did not trigger an error, even though `{{ 'foo' == constant('FOO') }}` did.
1 parent 39c4868 commit ba9a2b4

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"name": "Jeroen Versteeg"
99
}
1010
],
11-
"version": "1.0.5",
11+
"version": "1.0.6",
1212
"autoload": {
1313
"psr-4": {
1414
"AlisQI\\TwigQI\\": "src/"

src/Inspection/InvalidConstant.php

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Twig\Environment;
99
use Twig\Node\Expression\ConstantExpression;
1010
use Twig\Node\Expression\FunctionExpression;
11+
use Twig\Node\Expression\Test\ConstantTest;
1112
use Twig\Node\Expression\Variable\ContextVariable;
1213
use Twig\Node\Node;
1314
use Twig\NodeVisitor\NodeVisitorInterface;
@@ -17,20 +18,24 @@ class InvalidConstant implements NodeVisitorInterface
1718
public function enterNode(Node $node, Environment $env): Node
1819
{
1920
if (
20-
$node instanceof FunctionExpression &&
21-
$node->getAttribute('name') === 'constant'
21+
($node instanceof FunctionExpression && $node->getAttribute('name') === 'constant') ||
22+
$node instanceof ConstantTest
2223
) {
2324
$this->checkArguments($node);
2425
}
2526

2627
return $node;
2728
}
2829

29-
private function checkArguments(FunctionExpression $node): void
30+
private function checkArguments(FunctionExpression|ConstantTest $node): void
3031
{
3132
$arguments = $node->getNode('arguments');
3233

33-
if ($node->getAttribute('is_defined_test')) {
34+
// ignore `constant('foo') is defined`
35+
if (
36+
$node instanceof FunctionExpression &&
37+
$node->getAttribute('is_defined_test')
38+
) {
3439
return;
3540
}
3641

tests/InvalidConstantTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,18 @@ public function test_itValidatesConstants(string $constant, bool $isValid): void
2929
implode(', ', $this->errors)
3030
);
3131
}
32+
33+
/** @dataProvider getConstants */
34+
public function test_itValidatesConstantTest(string $constant, bool $isValid): void
35+
{
36+
$this->env->createTemplate("{{ 'this' is constant('$constant') }}");
37+
38+
self::assertEquals(
39+
$isValid,
40+
empty($this->errors),
41+
implode(', ', $this->errors)
42+
);
43+
}
3244

3345
public static function getInvalidConstants(): array
3446
{

0 commit comments

Comments
 (0)