Skip to content

Commit

Permalink
env 方法支持获取 true/false/empty/null 值
Browse files Browse the repository at this point in the history
  • Loading branch information
ueaner committed Oct 17, 2018
1 parent 1a2ab0a commit 99187bb
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
27 changes: 26 additions & 1 deletion src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ function mkdir_p($path, $mode = 0755)
/**
* Gets the value of an environment variable.
*
* @see https://github.com/laravel/framework/blob/master/src/Illuminate/Support/helpers.php env function
*
* @param string $key
* @param mixed $default
* @return mixed
Expand All @@ -199,7 +201,30 @@ function env($key, $default = null)
{
$value = getenv($key);

return $value === false ? $default : $value;
if ($value === false) {
return $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 (($valueLength = strlen($value)) > 1 && $value[0] === '"' && $value[$valueLength - 1] === '"') {
return substr($value, 1, -1);
}

return $value;
}
}

Expand Down
33 changes: 30 additions & 3 deletions tests/HelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,37 @@ public function testIsJson()

public function testEnv()
{
$this->assertEquals('localhost', env('SOLI_DATABASE_HOST', 'localhost'));
$this->assertEquals(null, env('NOT_EXISTS_ENV_KEY'));
$this->assertEquals('default value', env('NOT_EXISTS_ENV_KEY', 'default value'));

putenv("SOLI_DATABASE_HOST=192.168.56.102");
$this->assertEquals('192.168.56.102', env('SOLI_DATABASE_HOST'));
putenv('ENV_HELLO_WORLD=true');
$this->assertEquals(true, env('ENV_HELLO_WORLD'));
putenv('ENV_HELLO_WORLD=(true)');
$this->assertEquals(true, env('ENV_HELLO_WORLD'));

putenv('ENV_HELLO_WORLD=false');
$this->assertEquals(false, env('ENV_HELLO_WORLD'));
putenv('ENV_HELLO_WORLD=(false)');
$this->assertEquals(false, env('ENV_HELLO_WORLD'));

putenv('ENV_HELLO_WORLD=empty');
$this->assertEquals('', env('ENV_HELLO_WORLD'));
putenv('ENV_HELLO_WORLD=(empty)');
$this->assertEquals('', env('ENV_HELLO_WORLD'));

putenv('ENV_HELLO_WORLD=null');
$this->assertEquals(null, env('ENV_HELLO_WORLD'));
putenv('ENV_HELLO_WORLD=(null)');
$this->assertEquals(null, env('ENV_HELLO_WORLD'));

putenv('ENV_HELLO_WORLD="hello"');
$this->assertEquals('hello', env('ENV_HELLO_WORLD'));

putenv('ENV_HELLO_WORLD=hello');
$this->assertEquals('hello', env('ENV_HELLO_WORLD'));

putenv('ENV_HELLO_WORLD');
$this->assertEquals(null, env('ENV_HELLO_WORLD'));
}

public function testEnvFile()
Expand Down

0 comments on commit 99187bb

Please sign in to comment.