From c6ccd418e2c4d24ce87ef30e670b29e7de86af44 Mon Sep 17 00:00:00 2001 From: Adam Wathan Date: Fri, 25 Mar 2016 15:16:20 -0400 Subject: [PATCH] Don't explode when asking for a value from a bound array that isn't set --- src/AdamWathan/Form/Binding/BoundData.php | 4 ++-- tests/BindingTest.php | 27 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/AdamWathan/Form/Binding/BoundData.php b/src/AdamWathan/Form/Binding/BoundData.php index c4c4f5e..719b00a 100644 --- a/src/AdamWathan/Form/Binding/BoundData.php +++ b/src/AdamWathan/Form/Binding/BoundData.php @@ -31,8 +31,8 @@ protected function dataGet($target, $keyParts, $default) $key = array_shift($keyParts); - if (is_array($target) && isset($target[$key])) { - return $this->dataGet($target[$key], $keyParts, $default); + if (is_array($target)) { + return isset($target[$key]) ? $this->dataGet($target[$key], $keyParts, $default) : $default; } if (property_exists($target, $key) || method_exists($target, '__get')) { diff --git a/tests/BindingTest.php b/tests/BindingTest.php index 96aefae..a334449 100644 --- a/tests/BindingTest.php +++ b/tests/BindingTest.php @@ -155,6 +155,16 @@ public function testBindArray() $this->assertEquals($expected, $result); } + public function testBindArrayWithMissingKey() + { + $array = ['first_name' => 'John']; + $this->form->bind($array); + + $expected = ''; + $result = (string) $this->form->text('last_name'); + $this->assertEquals($expected, $result); + } + public function testBindNestedArray() { $array = [ @@ -178,6 +188,23 @@ public function testBindNestedArray() $this->assertEquals($expected, $result); } + public function testBindNestedArrayWithMissingKey() + { + $array = [ + 'address' => [ + 'tree' => [ + 'nested' => 'Bird' + ], + ], + ]; + + $this->form->bind($array); + + $expected = ''; + $result = (string) $this->form->text('address[notSet]'); + $this->assertEquals($expected, $result); + } + public function testBindNestedObject() { $object = json_decode(json_encode([