diff --git a/.gitignore b/.gitignore index 2f4dbc8..e6d0d39 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ vendor node_modules .idea +.vscode .stignore .stversions .stfolder .phpunit.result.cache + diff --git a/src/ChoiceFieldBuilder.php b/src/ChoiceFieldBuilder.php index 67fdf74..108a7e7 100644 --- a/src/ChoiceFieldBuilder.php +++ b/src/ChoiceFieldBuilder.php @@ -51,21 +51,40 @@ public function addChoices($choices) $choices = func_get_args(); } + $isIndexedArray = array_keys($choices) === range(0, count($choices) - 1); + foreach ($choices as $key => $value) { - $label = $choice = $value; + $parsed = $this->parseChoiceItem($key, $value, $isIndexedArray); + $this->addChoice($parsed[0], $parsed[1]); + } + + return $this; + } - if (is_array($choice)) { - $label = array_values($choice)[0]; - $choice = array_keys($choice)[0]; - } else if (is_string($key)) { - $choice = $key; - $label = $value; - } + /** + * Parse a choice item to extract the choice value and label. + * + * @param mixed $key The array key + * @param mixed $value The array value + * @param bool $isIndexedArray Whether the parent array is indexed (0, 1, 2...) + * @return array [$choice, $label] + */ + private function parseChoiceItem($key, $value, $isIndexedArray) + { + // Handle associative array choice: ['choice' => 'label'] + if (is_array($value)) { + $choice = array_keys($value)[0]; + $label = array_values($value)[0]; + return [$choice, $label]; + } - $this->addChoice($choice, $label); + // Handle a choice without a label, use the value as both choice and label + if ($isIndexedArray) { + return [$value, $value]; } - return $this; + // Handle choice array format where the key is explicitly defined + return [$key, $value]; } /** diff --git a/tests/ChoiceFieldBuilderTest.php b/tests/ChoiceFieldBuilderTest.php index 805513d..3ef0f04 100644 --- a/tests/ChoiceFieldBuilderTest.php +++ b/tests/ChoiceFieldBuilderTest.php @@ -9,7 +9,8 @@ class ChoiceFieldBuilderTest extends TestCase { use ArraySubsetAsserts; - + + public function testClassExists() { $this->assertTrue(class_exists('StoutLogic\AcfBuilder\ChoiceFieldBuilder')); @@ -97,4 +98,26 @@ public function testConfigInChoicesWithLabels() ] ], $config); } + + public function testNumericChoiceKeysWithLabels() + { + $subject = new ChoiceFieldBuilder('test_with_keys', 'radio', [ + 'choices' => [ + 1 => 'one', + 2 => 'two', + 5 => 'five', + '2.5' => '2 and a half', + ] + ]); + + $config = $subject->build(); + $this->assertArraySubset([ + 'choices' => [ + 1 => 'one', + 2 => 'two', + 5 => 'five', + '2.5' => '2 and a half', + ] + ], $config); + } }