Skip to content

Commit

Permalink
Fix error messages and PHP code format for type assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
drjayvee committed Oct 21, 2024
1 parent 539ecd4 commit 5f9b0f7
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions src/Assertion/AssertedTypesNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,17 @@ public function compile(Compiler $compiler): void
{
parent::compile($compiler); // compile the original TypesNode (which doesn't do anything)

$compiler->write('// type assertions' . PHP_EOL);

foreach (
$this->getNode('types')->getAttribute(
'mapping'
) as $name => ['type' => $type, 'optional' => $optional]
) {
$this->compileTypeAssertions($compiler, $name, $type, $optional);
}

$compiler->write('// end type assertions' . PHP_EOL);
}

private function compileTypeAssertions(Compiler $compiler, string $name, string $type, bool $optional): void
Expand All @@ -49,42 +53,47 @@ private function compileTypeAssertions(Compiler $compiler, string $name, string

public function assertVariableExists(Compiler $compiler, string $name): void
{
$compiler->raw('if (!array_key_exists(')
$compiler->write('if (!array_key_exists(')
->string($name)
->raw(', $context)) {')
->raw(', $context)) {' . PHP_EOL)
->indent()
->write('trigger_error("Non-optional variable \'$name\' is not set", E_USER_ERROR);')
->write('trigger_error(sprintf("Non-optional variable \'%s\' is not set", ')
->string($name)
->raw('), E_USER_ERROR);' . PHP_EOL)
->outdent()
->write('}');
->write('}' . PHP_EOL);
}

public function assertVariableIsNotNull(Compiler $compiler, string $name): void
{
$compiler->raw('if (array_key_exists(')
$compiler
->write('if (array_key_exists(')
->string($name)
->raw(', $context) && is_null($context[')
->string($name)
->raw('])) {')
->raw('])) {' . PHP_EOL)
->indent()
->write('trigger_error("Non-nullable variable \'$name\' is null", E_USER_ERROR);')
->write('trigger_error(sprintf("Non-nullable variable \'%s\' is null", ')
->string($name)
->raw('), E_USER_ERROR);' . PHP_EOL)
->outdent()
->write('}');
->write('}' . PHP_EOL);
}

private function assertType(Compiler $compiler, string $name, string $type): void
{
$compiler
->raw('if (($value = $context[')
->write('if (($value = $context[')
->string($name)
->raw('] ?? null) !== null && !\AlisQI\TwigQI\Assertion\AssertType::matches($value, ')
->string($type)
->raw(')) {' . PHP_EOL)
->indent()
->write('trigger_error(sprintf("Type for variable \'%s\' does not match", ')
->string($name)
->write('), E_USER_ERROR);' . PHP_EOL)
->raw('), E_USER_ERROR);' . PHP_EOL)
->outdent()
->write('}' . PHP_EOL)
->write('unset($value);');
->write('unset($value);' . PHP_EOL);
}
}

0 comments on commit 5f9b0f7

Please sign in to comment.