karser
karser

Reputation: 1693

nullable environment variables in Symfony

I know that env variables are string only. Symfony 3.4 supports env variables type casting. Is there a way to pass null value through int validator?

.env

DATABASE_PORT=
#I also tried DATABASE_PORT=null, DATABASE_PORT=~

parameters.yml

app.connection.port: '%env(int:DATABASE_PORT)%'
#I also tried env(?int, env(int?

I'm getting an error: "Non-numeric env var "DATABASE_PORT" cannot be cast to int." or "Invalid env(?int:DATABASE_PORT) name: only "word" characters are allowed."

In yml there are ~ or null signs used to pass null, e.g:

app.connection.port: ~

Upvotes: 8

Views: 3829

Answers (2)

Pavel
Pavel

Reputation: 31

Try use fallback param:

app.connection.port: '%env(int:default::DATABASE_PORT)%'

Upvotes: 3

Gregoire Ducharme
Gregoire Ducharme

Reputation: 1106

Someone asked in the doc:

Is it, or will it be possible to define your own operator? Like %env(myDecoder:API_PASSWORD)%, which will decrypt the environment value into something usable.

class MyDecoder implements EnvironmentOperator {
  public function resolve(string $value): string { 
    // magic stuff for decryption 
    return $value;
  }
}

And the answer was:

yes, you just need to create a service that implements EnvProviderInterface and tag it with container.env_provider.

You could create an operator to accept null as an int

Upvotes: 1

Related Questions