Skip to content
Permalink
Browse files

Adds default value parameter to Request::env().

  • Loading branch information...
michaelze committed Sep 20, 2015
1 parent f3f716e commit b3ebd14dec37728500509f5df7cac6b2c46d2d5c
Showing with 31 additions and 2 deletions.
  1. +4 −2 src/Network/Request.php
  2. +27 −0 tests/TestCase/Network/RequestTest.php
@@ -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;
@@ -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;
}
/**
@@ -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.
*

0 comments on commit b3ebd14

Please sign in to comment.
You can’t perform that action at this time.