Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
vendor
node_modules
.idea
.vscode
.stignore
.stversions
.stfolder
.phpunit.result.cache

39 changes: 29 additions & 10 deletions src/ChoiceFieldBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}

/**
Expand Down
25 changes: 24 additions & 1 deletion tests/ChoiceFieldBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
class ChoiceFieldBuilderTest extends TestCase
{
use ArraySubsetAsserts;



public function testClassExists()
{
$this->assertTrue(class_exists('StoutLogic\AcfBuilder\ChoiceFieldBuilder'));
Expand Down Expand Up @@ -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);
}
}