Twig icon indicating copy to clipboard operation
Twig copied to clipboard

πŸ’‘ Node `assert`❔

Open smnandre opened this issue 1 year ago β€’ 4 comments

Acting as a spinoff to #4165 Add tag to declare variable types (as I don't want to disrupt the main conversation too much πŸ˜…)

The idea is to introduce assertions.

I'm opening this to gather feedback and ideas. I'd like to see if there's something interesting hereβ€”or not. :)

This could enhance static analysis, define contracts in templates, and serve as a validator during includes/rendering.

{% assert name string %}
{% assert size in ['sm', 'md', 'lg'] %}

Open to any feedback :)

smnandre avatar Aug 24 '24 21:08 smnandre

Usage / syntax examples

Langage Code example
PHP assert(in_array($size, ['sm', 'md']));
Python assert size in ['sm', 'md']
Java assert java.util.Arrays.asList("sm", "md").contains(size);
C assert(strcmp(size, "sm") == 0 || strcmp(size, "md") == 0);
JavaScript console.assert(["sm", "md"].includes(size));
C++ assert(size == "sm" || size == "md");
Ruby raise 'Assertion failed' unless ['sm', 'md'].include?(size)

(Table made with some gpt - for representational purposes only)

smnandre avatar Aug 24 '24 21:08 smnandre

When it comes to asserting variable types, that can be left over to extensions like TwigQI, once types is merged.

I do like the idea of using assert for expressions.

There's currently no way to intentionally throw an Exception of trigger a warning (aside from something silly like {{ [].foo }}).

I'd propose that the assert tag should have an optional message as part of its spec:

{% assert <expression> [message string] %}

@ruudk is working on compiling Twig templates to PHP in such a way that PHPStan can work its magic. If the assert tag gets a similar treatment, with properly typed variables, we can take a huge leap in template quality.

drjayvee avatar Aug 26 '24 09:08 drjayvee

@ruudk is working on compiling Twig templates to PHP in such a way that PHPStan can work its magic. If the assert tag gets a similar treatment, with properly typed variables, we can take a huge leap in template quality.

I'm curious to see how that would look like... but also if that's something we can include in the "default" Twig compilation (I suppose this is based on attributes/annotations with no runtime side-effects).

fabpot avatar Aug 26 '24 09:08 fabpot

You can read more about TwigStan here: https://github.com/twigphp/Twig/discussions/4233

ruudk avatar Aug 26 '24 09:08 ruudk

Now that we have the types tag, can we close this one?

fabpot avatar Oct 03 '24 11:10 fabpot

Now that we have the types tag, can we close this one?

In the end, i think this "assert" would be more related to assertions / tests than strict typing...

But I do agree we should focus on the "types" tag and see how / why it is used, the features it enables, ...

(and we can reopen here if needed later)

smnandre avatar Oct 04 '24 21:10 smnandre