Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support boolean strings in environment variables #3975

Closed
timeverts opened this issue Mar 11, 2019 · 0 comments
Closed

Support boolean strings in environment variables #3975

timeverts opened this issue Mar 11, 2019 · 0 comments

Comments

@timeverts
Copy link

Description

Currently, setting an environment variable value in .env to true or false string literals and fetching that using Craft::parseEnv() does not return the boolean equivalent value, as might be expected by many developers. Instead the string value 'true' or 'false' is returned, so boolean comparisons on the parsed environment variable always equate to true.

Some other popular frameworks natively implement this string to boolean conversion functionality in their environment parsing methods. For example, Laravel's environment parsing method does the following:

    /**
     * Gets the value of an environment variable. Supports boolean, empty and null.
     *
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed
     */
    function env($key, $default = null)
    {
        $value = getenv($key);
        if ($value === false) {
            return value($default);
        }
        switch (strtolower($value)) {
            case 'true':
            case '(true)':
                return true;
            case 'false':
            case '(false)':
                return false;
            case 'empty':
            case '(empty)':
                return '';
            case 'null':
            case '(null)':
                return;
        }
        if (Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
            return substr($value, 1, -1);
        }
        return $value;
    }

It would be great if Craft::parseEnv() could be made more intelligent to handle boolean type environment variables and alias values.

FYI: There is an interesting discussion about the support of boolean environment variables on the official phpdotenv github.

Steps to reproduce

  1. Define an environment variable in .env with a false string value (e.g. TEST_MODE=false)
  2. Parse it: $isTestMode = Craft::parseEnv('TEST_MODE')
  3. Test it: echo ($isTestMode ? 'In Test Mode' : 'Not In Test Mode'); outputs In Test Mode instead of Not In Test Mode.

Additional info

  • Craft version: 3.1.17.1
  • PHP version: 7.1
  • Database driver & version: mySQL 5.7.14
  • Plugins & versions: N/A
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant