Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-scalar ENVs for use as Symfony Parameter

I'm trying to use ENVs to set my parameters in Symfony2. The scalar values are easy enough, but I have parameters that are arrays that I need to set somehow with ENVs.

The parameter in question:

parameters:
  redis.servers:
    - { host: 127.0.0.1, port: 6379 }
    - { host: other, port: 6379 }
    # and so on

The kicker here is that the array of servers can change dynamically, so I can't just assume there's 2.

What I hoped to do (but this just gives me a string of json):

SYMFONY__REDIS__SERVERS=[{"host":"127.0.0.1","port":"6379"}]

Is this possible? Any work-arounds that are feasible? There are multiple bundles we're using that accept array/object parameters, so I can't do an update there to process the param. It would have to be app level, if anything.

Thanks.

like image 258
jmar Avatar asked Nov 10 '22 20:11

jmar


1 Answers

I was able to solve this by updating the AppKernel to override the getEnvParameters() method of the parent Kernel. This method only runs on parameters that the Kernel already found in the ENV (technically from $_SERVER). I like it because it won't run on the entire parameter stack, nor the entire $_SERVER array.

protected function getEnvParameters()
{
    $parameters = parent::getEnvParameters();
    foreach ($parameters as &$parameter) {
        if (is_string($parameter)) {
            $decoded = json_decode($parameter, true);
            // we only care about arrays (or objects that get turned into arrays)
            if (!json_last_error() && is_array($decoded)) {
                $parameter = $decoded;
            }
        }
    }

    return $parameters;
}
like image 127
jmar Avatar answered Nov 15 '22 10:11

jmar