Testing the type of a variable in a Twig template

Published on 2020-06-15 • Modified on 2020-06-15

In this snippet, we will see how to test the type of a variable in a Twig template. We will create a small extension for this purpose. In the following demo, first, I display the variables that will be used. They are declared in plain PHP, so we are sure of the type. Then I present the test matrix where each variable is tested against each type. To display the test result, I use a ternary expression:
{{ varNumeric is of_type('int') ? 'βœ…' : '❌' }}


HTML demo of snippet

Variables

    /**
     * This function belongs to the "App\Data\SnippetData" class.
     *
     * @see templates/snippet/code/_95_demo.html.twig
     */
    public function data95(array $data): array
    {
        $data['varArray'] = [4, 5, 6];
        $data['varBool'] = true;
        $data['varObject'] = $this;
        $data['varClass'] = $this;
        $data['varFloat'] = 3.14;
        $data['varInt'] = 15;
        $data['varNumeric'] = '555';
        $data['varScalar'] = 'foo';
        $data['varString'] = 'bar';

        return $data;
    }
⬇var is of_type('type') ➑ array bool object class float int numeric scalar string
varArray βœ… ❌ ❌ ❌ ❌ ❌ ❌ ❌ ❌
varBool ❌ βœ… ❌ ❌ ❌ ❌ ❌ βœ… ❌
varObject ❌ ❌ βœ… ❌ ❌ ❌ ❌ ❌ ❌
varClass (App\Data\SnippetData) ❌ ❌ βœ… βœ… ❌ ❌ ❌ ❌ ❌
varFloat ❌ ❌ ❌ ❌ βœ… ❌ βœ… βœ… ❌
varInt ❌ ❌ ❌ ❌ ❌ βœ… βœ… βœ… ❌
varNumeric ❌ ❌ ❌ ❌ ❌ ❌ βœ… βœ… βœ…
varScalar ❌ ❌ ❌ ❌ ❌ ❌ ❌ βœ… βœ…
varString ❌ ❌ ❌ ❌ ❌ ❌ ❌ βœ… βœ…

<?php declare(strict_types=1);

// src/Twig/Extension/TypeExtension.php

namespace App\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigTest;

final class TypeExtension extends AbstractExtension
{
    public function getTests(): array
    {
        return array('of_type' => new TwigTest('of_type', [$this, 'ofType']));
    }

    /**
     * @param mixed $var
     */
    public function ofType($var, string $test, string $class = null): bool
    {
        switch ($test) {
            case 'array':
                return is_array($var);

            case 'bool':
                return is_bool($var);

            case 'object':
                return is_object($var);

            case 'class':
                return is_object($var) === true && $class === get_class($var);

            case 'float':
                return is_float($var);

            case 'int':
                return is_int($var);

            case 'numeric':
                return is_numeric($var);

            case 'scalar':
                return is_scalar($var);

            case 'string':
                return is_string($var);

            default:
                throw new \InvalidArgumentException(sprintf('Invalid "%s" type test.', $test));
        }
    }
}

 More on Stackoverflow  More on the web  Random snippet