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') ? 'βœ…' : '❌' }}


<?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 ['of_type' => new TwigTest('of_type', $this->ofType(...))];
    }

    public function ofType(mixed $var, string $test, ?string $class = null): bool
    {
        return match ($test) {
            'array' => \is_array($var),
            'bool' => \is_bool($var),
            'object' => \is_object($var),
            'class' => \is_object($var) && $class === \get_class($var),
            'float' => \is_float($var),
            'int' => \is_int($var),
            'numeric' => is_numeric($var),
            'scalar' => \is_scalar($var),
            'string' => \is_string($var),
            default => throw new \InvalidArgumentException(\sprintf('Invalid "%s" type test.', $test)),
        };
    }
}
HTML demo of the snippet

Variables

     * This function belongs to the "App\Data\SnippetData" class.
     *
     * @see templates/snippet/code/_95_demo.html.twig
     *
     * @param array<string,mixed> $data
     *
     * @return array<string,mixed>
     */
    public function data95(array $data): array
    {
        $data['types'] = ['array', 'bool', 'object', 'class', 'float', 'int', 'numeric', 'scalar', 'string'];
        $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 ❌ ❌ ❌ ❌ ❌ ❌ ❌ βœ… βœ…

 More on Stackoverflow  More on the web  Random snippet

  Work with me!