Skip to content

Commit

Permalink
Adds default value parameter to Request::env().
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelze committed Sep 20, 2015
1 parent f3f716e commit b3ebd14
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Network/Request.php
Expand Up @@ -1227,10 +1227,12 @@ public function cookie($key)
*
* @param string $key The key you want to read/write from/to.
* @param string|null $value Value to set. Default null.
* @param string|null $default Default value when trying to retrieve an environment
* variable's value that does not exist. The value parameter must be null.
* @return $this|string|null This instance if used as setter,
* if used as getter either the environment value, or null if the value doesn't exist.
*/
public function env($key, $value = null)
public function env($key, $value = null, $default = null)
{
if ($value !== null) {
$this->_environment[$key] = $value;
Expand All @@ -1242,7 +1244,7 @@ public function env($key, $value = null)
if (!array_key_exists($key, $this->_environment)) {
$this->_environment[$key] = env($key);
}
return $this->_environment[$key];
return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
}

/**
Expand Down
27 changes: 27 additions & 0 deletions tests/TestCase/Network/RequestTest.php
Expand Up @@ -499,6 +499,33 @@ public function testMethodOverrides()
$this->assertEquals('POST', $request->env('ORIGINAL_REQUEST_METHOD'));
}

/**
* Tests the env() method returning a default value in case the requested environment variable is not set.
*/
public function testDefaultEnvValue()
{
$_ENV['DOES_NOT_EXIST'] = null;
$request = new Request();
$this->assertNull($request->env('DOES_NOT_EXIST'));
$request = new Request();
$this->assertEquals('default', $request->env('DOES_NOT_EXIST', null, 'default'));
$_ENV['DOES_EXIST'] = 'some value';
$request = new Request();
$this->assertEquals('some value', $request->env('DOES_EXIST'));
$request = new Request();
$this->assertEquals('some value', $request->env('DOES_EXIST', null, 'default'));
$_ENV['EMPTY_VALUE'] = '';
$request = new Request();
$this->assertEquals('', $request->env('EMPTY_VALUE'));
$request = new Request();
$this->assertEquals('', $request->env('EMPTY_VALUE', null, 'default'));
$_ENV['ZERO'] = '0';
$request = new Request();
$this->assertEquals('0', $request->env('ZERO'));
$request = new Request();
$this->assertEquals('0', $request->env('ZERO', null, 'default'));
}

/**
* Test the clientIp method.
*
Expand Down

0 comments on commit b3ebd14

Please sign in to comment.