From b92686dc4c2a50c9528777734fecb1a615d3d7e0 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 10 Nov 2016 19:08:19 -0500 Subject: [PATCH] Implement getParam() Add getParam() which allows us to fully deprecate param(). --- src/Http/ServerRequest.php | 22 +++++++++++++++++----- tests/TestCase/Network/RequestTest.php | 22 +++++++++++++++++++++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/src/Http/ServerRequest.php b/src/Http/ServerRequest.php index edccf35df5f..68d44d54d87 100644 --- a/src/Http/ServerRequest.php +++ b/src/Http/ServerRequest.php @@ -1459,11 +1459,7 @@ public function param($name, ...$args) return $this; } - if (!isset($this->params[$name])) { - return Hash::get($this->params, $name, false); - } - - return $this->params[$name]; + return $this->getParam($name); } /** @@ -1742,6 +1738,22 @@ public function withParam($name, $value) return $copy; } + /** + * Safely access the values in $this->params. + * + * @param string $name The name of the parameter to get. + * @param mixed $default The default value if $name is not set. + * @return mixed + */ + public function getParam($name, $default = false) + { + if (!isset($this->params[$name])) { + return Hash::get($this->params, $name, $default); + } + + return $this->params[$name]; + } + /** * Return an instance with the specified request attribute. * diff --git a/tests/TestCase/Network/RequestTest.php b/tests/TestCase/Network/RequestTest.php index 7ae3bc97f4c..16861decef7 100644 --- a/tests/TestCase/Network/RequestTest.php +++ b/tests/TestCase/Network/RequestTest.php @@ -2587,7 +2587,7 @@ public function testDataWritingFalsey() * * @dataProvider paramReadingDataProvider */ - public function testParamReading($toRead, $expected) + public function testGetParam($toRead, $expected) { $request = new Request('/'); $request->addParams([ @@ -2603,6 +2603,26 @@ public function testParamReading($toRead, $expected) 'zero' => '0', ]); $this->assertSame($expected, $request->param($toRead)); + $this->assertSame($expected, $request->getParam($toRead)); + } + + /** + * Test getParam returning a default value. + * + * @return void + */ + public function testGetParamDefault() + { + $request = new Request([ + 'params' => [ + 'controller' => 'Articles', + 'null' => null, + ] + ]); + $this->assertSame('Articles', $request->getParam('controller', 'default')); + $this->assertSame('default', $request->getParam('null', 'default')); + $this->assertNull($request->getParam('unset', null)); + $this->assertFalse($request->getParam('unset')); } /**