Twig: Creating a variable named "null" is valid

Created on 22 Apr 2016  路  7Comments  路  Source: twigphp/Twig

Hi,

I was making some experiments with Twig variables management and I found a weird edge case. Indeed you cannot create a Twig variable called true or false but it works if you create a variable called null.

Look at the following snippet:

{% set null = 'hello' %}
{{ 'BEGIN VARIABLE CALLED NULL' }}
{{ null }}
{% if null is not null %}
    NULL = {{ null }}
{% endif %}
{{ 'END VARIABLE CALLED NULL' }}

This template compiles without any issues and renders the following output when it's evaluated:

BEGIN VARIABLE CALLED NULL
END VARIABLE CALLED NULL

The compiled version is the following:

<?php

/* view.twig */
class __TwigTemplate_42e679c29ec1ae34fc295d195e08fffe178e7ef502d6464c900c66cc092f89ee extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $context["null"] = "hello";
        // line 2
        echo "BEGIN VARIABLE CALLED NULL";
        echo "
";
        // line 3
        if ( !(null === null)) {
            // line 4
            echo "    NULL = ";
            echo null;
            echo "
";
        }
        // line 6
        echo "END VARIABLE CALLED NULL";
        echo "
";
    }

    public function getTemplateName()
    {
        return "view.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  33 => 6,  27 => 4,  25 => 3,  21 => 2,  19 => 1,);
    }
}
/* {% set null = 'hello' %}*/
/* {{ 'BEGIN VARIABLE CALLED NULL' }}*/
/* {% if null is not null %}*/
/*     NULL = {{ null }}*/
/* {% endif %}*/
/* {{ 'END VARIABLE CALLED NULL' }}*/
/* */

I know it sounds weird and its an edge case but I think we should forbit the null keyword as a structure name.

Most helpful comment

Yes. It makes sense to prevent a variable name from being called null.

Nice detective work by the way. I wonder what "dangerous" Twig things are you working on 馃榿

All 7 comments

Yes. It makes sense to prevent a variable name from being called null.

Nice detective work by the way. I wonder what "dangerous" Twig things are you working on 馃榿

You cannot imagine!

We should indeed forbid it (it does not work properly anyway). We have the same issue with none btw (which is an alias for null)

Actually, we don't have the bug for none. It was checked properly. So this is a mistake when adding support for null as a synonym: https://github.com/twigphp/Twig/blob/babe6fca0eea3bac736017f817fb7d26147e4792/lib/Twig/ExpressionParser.php#L542

btw, we have the issue for uppercases names though: TRUE, FALSE, NULL and NONE

Good to know! I'll make a patch this weekend ;)

Was this page helpful?
0 / 5 - 0 ratings