Home > Software design >  Symfony constraint-mapping do not see env variables
Symfony constraint-mapping do not see env variables

Time:06-20

I have following .env file:

VAR=8888

I want to use this variable from .env file in the constraint config file. So I do this:

<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    <class name="App\Entity">
        <property name="page">
            <constraint name="EqualTo">
                <option name="value">%env(string:VAR)%</option>
            </constraint>
        </property>
    </class>
</constraint-mapping>

But the env value is not interpreted. It just prints sth like this: \"%env(string:VAR)%\"

Also I have tried first to set parameter in config.yaml, like this:

parameters:
    var: '%env(resolve:VAR)%'

And then try to use like this:

...
<constraint name="EqualTo">
    <option name="value">%var%</option>
</constraint>
...

But it also does not work.

I am using php v. 8.1 with symfony v. 6.1 I have tried to remove cache and restart docker containers but it didn't help :(

CodePudding user response:

One solution from this user is to create a custom validator, similar to this:

class CustomConstraintValidator extends ConstraintValidator
{
    private string $var

    public function __construct(string $var
    {
        $this->var = $var
    }

    public function validate($value, Constraint $constraint): void
    {
        if ($value === $this->var) {
            return;
        }
        $this->context->buildViolation($constraint->message)->addViolation();
    }
}

Then create a custom constraint:

class CustomConstraint extends Constraint
{
    public string $message = 'Invalid VAR';
}

Then set up parameter in services.yaml:

...
services:
    CustomConstraintValidator:
        arguments:
            $var: '%env(resolve:VAR)%'

And then use it in XML file like this:

...
<property name="page">
     <constraint name="CustomConstraint" />
</property>
  • Related