skip to Main Content

I have a Symfony validation constraint that removes all Twig tags with regular expressions before counting characters and validating based on character length limits. (My form allows people to enter a limited subset of Twig tags in a field.) So it does something like this:

    $parsedLength = mb_strlen(
        preg_replace('/{%[^%]*%}/', '', $stringValue)
    );

… then builds violations if the $parsedLength value is too long.

This works, but it doesn’t sit right with me. Is there a way I can pass a service of some sort into my validation class and then use that service to render the text without Twig tags? That seems like it would be the more symfonic way to do things, rather than using regular expressions.

2

Answers


  1. can you share your code please? As i understand, you’re applying the validation logic inside the constraint, but that should go inside a validator.

    The right steps to achieve the expected result are:

    1. Create a Custom Constraint that contains no validation logic
    2. Create a Custom Validator for that Constraint and configure it as a service. The validator should accept your service as a constructor argument.

    An example:

    twig_char_lenght_validator:
        class: ...TwigCharLengthValidator
        arguments:
            - "@your.service"
    
    1. Complete your Validator logic using the injected service.

    Official doc: https://symfony.com/doc/current/validation/custom_constraint.html

    Login or Signup to reply.
  2. I’m not 100% this is what you are asking for but you can create a template from your input and then render it. Certainly get’s rid of all the twig stuff though I am not sure if you always know what the variables will be.

    I poked around a bit and all the examples seem quite old and I was not sure if things would still work. Could not even find an example in the docs though I’m sure it is there somewhere. In any event:

    use TwigEnvironment;
    
    #[AsCommand(
        name: 'app:twig',
        description: 'Add a short description for your command',
    )]
    class TwigCommand extends Command
    {
        public function __construct(private Environment $twig)
        {
            parent::__construct();
        }
    
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $input = '{{ hello }}';
            // This is the important line
            $template = $this->twig->createTemplate($input);
            $rendered = $template->render(['hello' => 'Hello World']);
            echo $rendered . "n";
    
            return Command::SUCCESS;
        }
    }
    

    If nothing else this allows you to validate the actual template as well. But as already mentioned, I’m not really sure what parsed length is supposed to mean. Regardless, createTemplate is an interesting (to me) method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search