Skip to content
This repository has been archived by the owner on Mar 28, 2022. It is now read-only.

Commit

Permalink
Merge pull request #13 from MichaelGooden/feature/nested-values-prese…
Browse files Browse the repository at this point in the history
…rve-keys

Optionally preserve keys in Field nested values
  • Loading branch information
DASPRiD committed Apr 19, 2017
2 parents 94ebc0b + 79c43a7 commit 665f78f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,19 @@ public function getIndexes() : array
/**
* @return string[]
*/
public function getNestedValues() : array
public function getNestedValues(bool $preserveKeys = false) : array
{
$values = [];

foreach ($this->getIndexes() as $index) {
$key = $this->key . '[' . $index . ']';

if ($this->data->hasKey($key)) {
$values[] = $this->data->getValue($key);
if ($preserveKeys) {
$values[$index] = $this->data->getValue($key);
} else {
$values[] = $this->data->getValue($key);
}
}
}

Expand Down
25 changes: 25 additions & 0 deletions test/FieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,29 @@ public function testGetNestedValues()

$this->assertSame(['bar0', 'bar1'], $field->getNestedValues());
}

public function testGetNestedValuesPreserveKeys()
{
$field = new Field('foo', '', new FormErrorSequence(), Data::fromFlatArray([
'foo[bar]' => 'bar0',
'foo[baz]' => 'baz0',
'foo[1][baz]' => 'bar2',
]));

$this->assertSame([
'bar' => 'bar0',
'baz' => 'baz0'
], $field->getNestedValues(true));
}

public function testGetNestedValuesNoPreserveKeys()
{
$field = new Field('foo', '', new FormErrorSequence(), Data::fromFlatArray([
'foo[bar]' => 'bar0',
'foo[baz]' => 'baz0',
'foo[1][baz]' => 'bar2',
]));

$this->assertSame(['bar0', 'baz0'], $field->getNestedValues());
}
}

0 comments on commit 665f78f

Please sign in to comment.