Skip to content

[DependencyInjection] [DX] Support for JSON string environment variables #23823

@Pierstoval

Description

@Pierstoval
Q A
Bug report? no
Feature request? yes
BC Break report? no
RFC? no
Symfony version master (new feature), so 3.4 or 4.1

A year ago, a proposal was made to support composite env vars (#17689), and was closed as "won't fix".

Today, I think we can take benefit from the %env(MY_VAR)% syntax to support other kind of environment vars than simple strings.

Usage in the real world

I don't know many environments and platforms, but I can say that Platform.sh defines certain env vars as serialized JSON strings, and we can use them in our applications by deserializing them with json_encode().

This gave me the idea of a new implementation for env vars as array: json strings.

Base Proposal: %json_env()%

We could add a new env var handling system with a syntax like %json_env(MY_VAR)% that would, at runtime (else, it's useless to have env vars) retrieve this env var and run json_encode(getenv('MY_VAR'), true) on it.

Currently, deserializing can be as simple as this:

$ ARRAY_VAR='{"a":1,"b":2}' php -r 'dump(json_decode(getenv("ARRAY_VAR"), true));'
array:2 [
  "a" => 1
  "b" => 2
]

Adding this to Symfony's service container doesn't seem like a big issue to me, but I'm posting an issue for advices 😄

I don't have any performance benchmark on this, but if we are looking for performances, we might as well go with PHP unserialize(), but I'm not sure this would be really DX then...

Bonus: deep parsing

As we can have control over this json_encode() call (by using a method in the container, like
$this->parseJsonEnvVar($envVarName)) we can also navigate through the array and look for other %env()% or %json_env()% strings to parse them too, still at runtime. However, it might lead to performance issues when dealing with too much nested env vars. But this is just a bonus proposal 😉

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    DXDX = Developer eXperience (anything that improves the experience of using Symfony)DependencyInjectionFeature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions