Skip to content

Made getValue consistent to setValue. #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 12, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 10 additions & 3 deletions src/ArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,16 @@ public static function getValue($array, $key, $default = null)
return $array[$key];
}

if (($pos = strrpos($key, '.')) !== false) {
$array = static::getValue($array, substr($key, 0, $pos), $default);
$key = substr($key, $pos + 1);
if (strpos($key, '.') !== false) {
$keys = explode('.', $key);
while (count($keys) != 0) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the foreach loop

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree. Would be more readable.

$key = array_shift($keys);
if (!(isset($array[$key]) || array_key_exists($key, $array))) {
return $default;
}
$array = $array[$key];
}
return $array;
}

if (is_object($array)) {
Expand Down
15 changes: 15 additions & 0 deletions tests/ArrayHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,21 @@ public function testGetValue($key, $expected, $default = null): void
$this->assertEquals($expected, ArrayHelper::getValue($array, $key, $default));
}

/**
* @see https://github.com/yiisoft/arrays/issues/1
*/
public function testGetValueConsistentWithSetValue()
{
$array = [
'a.b' => [
'c' => 'value1',
],
];
$this->assertEquals(null, ArrayHelper::getValue($array, 'a.b.c'));
ArrayHelper::setValue($array, 'a.b.c', 'newValue');
$this->assertEquals('newValue', ArrayHelper::getValue($array, 'a.b.c'));
}

public function testGetValueObjects(): void
{
$arrayObject = new ArrayObject(['id' => 23], ArrayObject::ARRAY_AS_PROPS);
Expand Down