platformsh / symfonyflex-bridge

Bridge library for running Symfony Flex on Platform.sh
MIT License
30 stars 15 forks source link

Use Setenv as well #10

Closed Crell closed 6 years ago

Crell commented 6 years ago

See #9 for background.

pjcdawkins commented 6 years ago

Is $_SERVER otherwise a normal way to access environment variables? not $_ENV?

Crell commented 6 years ago

Unfortunately PHP is rather inconsistent. :frowning:

At startup, it populates $_ENV, $_SERVER, and getenv(), UNLESS it's running through the built in web server in which case only getenv() works. (Or maybe $_SERVER does as well, I forget.)

After startup they are not kept in sync at all, and all can be changed independently.

I don't know what constitutes "normal way to access"; I'd say getenv(), but I cannot speak for what every system is doing.

pjcdawkins commented 6 years ago

At startup, it populates $_ENV, $_SERVER, and getenv(), UNLESS it's running through the built in web server in which case only getenv() works. (Or maybe $_SERVER does as well, I forget.)

FTR it depends on the variables_order ini setting, so the built-in server populates those variables if you use

php -d variables_order=egpcs -S 127.0.01:8000 -t docroot

So... if I was being picky I'd suggest something like:

function addToEnv(string $name, string $value): void {
    if (!putenv("$name=$value")) {
        throw new \RuntimeException('Failed to create environment variable: '.$name);
    }
    $order = ini_get('variables_order');
    if (stripos($order, 'e') !== false) {
        $_ENV[$name] = $value;
    }
    if (stripos($order, 's') !== false) {
        if (strpos($name, 'HTTP_') !== false) {
            throw new \RuntimeException('Refusing to add ambiguous environment variable '.$name.' to $_SERVER');
        }
        $_SERVER[$name] = $value;
    }
}

But I notice Symfony doesn't care: https://github.com/symfony/symfony/blob/b1a41a4812663910912f11a0e9fe10e0c9f96ef6/src/Symfony/Component/HttpKernel/Kernel.php#L113-L117

Crell commented 6 years ago

I don't mind picky. :smile: Let's do that. Tests still pass.