Tester le type d'une variable dans un template Twig

Publié le 15/06/2020 • Actualisé le 15/06/2020


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous allons voir comment Tester le type d'une variable dans un template Twig. Pour ce faire nous allons créer une petite extension. Dans la démo suivante, tout d'abord je déclare les variables qui vont être utilisées. Elles sont déclarées en PHP pour être sûr du type créé. Ensuite, j'affiche la matrice de test ou chaque variable est testée avec chaque type. Pour afficher le résultat du test, j'utilise une expression ternaire :
{{ 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)),
        };
    }
}
Démo HTML du 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

 Plus sur Stackoverflow  Plus sur le web  Snippet aléatoire

  Travaillez avec moi !