Skip to content

Commit

Permalink
Bugfix: dot operation validation works for nullable types
Browse files Browse the repository at this point in the history
The following template will now trigger two Errors:
```
{% types {
  foo: '?string',
  bar: '?\\Exception',
} %}
{{ foo.bad }}
{{ bar.bad }}
```
  • Loading branch information
drjayvee committed Nov 27, 2024
1 parent fc61537 commit 39c4868
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"name": "Jeroen Versteeg"
}
],
"version": "1.0.4",
"version": "1.0.5",
"autoload": {
"psr-4": {
"AlisQI\\TwigQI\\": "src/"
Expand Down
4 changes: 4 additions & 0 deletions src/Inspection/InvalidDotOperation.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ private function checkOperation(string $name, string $attribute, NodeLocation $l

$type = $variableTypeCollector->getDeclaredType($name);

if (str_starts_with($type, '?')) {
$type = substr($type, 1);
}

if (in_array($type, self::UNSUPPORTED_TYPES)) {
trigger_error(
sprintf('Invalid dot operation on unsupported type \'%s\' (at %s)', $type, $location),
Expand Down
20 changes: 20 additions & 0 deletions tests/InvalidDotOperationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ public static function getInvalidTypesForDotOperator(): array
['string'],
['number'],
['boolean'],
['?string'],
['?number'],
['?boolean'],
];
}

Expand Down Expand Up @@ -222,6 +225,23 @@ public function test_itValidatesDotOperationOnObjects(string $type, string $attr
);
}

/** @dataProvider getClassNamesAndAttributes */
public function test_itValidatesDotOperationOnObjectsEvenIfNullable(string $type, string $attribute, bool $isValid): void
{
$this->env->createTemplate(
<<<EOF
{% types {foo: '?$type'} %}
{{ foo.$attribute }}
EOF
);

self::assertEquals(
$isValid,
empty($this->errors),
implode(', ', $this->errors)
);
}

public static function getAttributeShorthands(): array
{
$dummyClassFqn = '\\\\AlisQI\\\\TwigQI\\\\Tests\\\\Type\\\\Dummy';
Expand Down

0 comments on commit 39c4868

Please sign in to comment.