From 7d7800e5e77914b47528f19cc56b65184adf2842 Mon Sep 17 00:00:00 2001 From: Robbie Averill Date: Tue, 10 May 2016 10:27:36 +1200 Subject: [PATCH] Fix for array to string conversion in DropdownField * Resolves #4835 * Add unit test to cover array values * Add value assertion --- forms/DropdownField.php | 7 ++++++- tests/forms/DropdownFieldTest.php | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/forms/DropdownField.php b/forms/DropdownField.php index 89feef34a..83fa88edf 100644 --- a/forms/DropdownField.php +++ b/forms/DropdownField.php @@ -172,7 +172,12 @@ class DropdownField extends FormField { if($value) { $selected = ($value == $this->value); } else { - $selected = ($value === $this->value) || (((string) $value) === ((string) $this->value)); + // Safety check against casting arrays as strings in PHP>5.4 + if(!is_array($value) && !is_array($this->value)) { + $selected = ($value === $this->value) || (((string) $value) === ((string) $this->value)); + } else { + $selected = ($value === $this->value); + } } $this->isSelected = $selected; diff --git a/tests/forms/DropdownFieldTest.php b/tests/forms/DropdownFieldTest.php index 481da561b..a43f8ee09 100644 --- a/tests/forms/DropdownFieldTest.php +++ b/tests/forms/DropdownFieldTest.php @@ -223,6 +223,32 @@ class DropdownFieldTest extends SapphireTest { $this->assertEquals(count($disabledOptions), 0, 'There are no disabled options'); } + /** + * The Field() method should be able to handle arrays as values in an edge case. If it couldn't handle it then + * this test would trigger an array to string conversion PHP notice + * + * @dataProvider arrayValueProvider + */ + public function testDropdownWithArrayValues($value) { + $field = $this->createDropdownField(); + $field->setValue($value); + $this->assertInstanceOf('HTMLText', $field->Field()); + $this->assertSame($value, $field->Value()); + } + + /** + * @return array + */ + public function arrayValueProvider() { + return array( + array(array()), + array(array(0)), + array(array(123)), + array(array('string')), + array('Regression-ish test.') + ); + } + /** * Create a test dropdown field, with the option to * set what source and blank value it should contain