Skip to content

Commit

Permalink
Merge pull request traderinteractive#5 from chadicus/fea/getNested
Browse files Browse the repository at this point in the history
Add Arrays::getNested
  • Loading branch information
chadicus committed Mar 31, 2016
2 parents cac6389 + 64fdfa0 commit bd9114b
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/Arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -411,4 +411,49 @@ public static function nullifyEmptyStrings(array &$array)
}
}
}

/**
* Traverses the given $array using the key path specified by $delimitedKey and returns the final value.
*
* Example:
* <br />
* <pre>
* use DominionEnterprises\Util\Arrays;
* $array = [
* 'db' => [
* 'host' => 'localhost',
* 'login' => [
* 'username' => 'scott',
* 'password' => 'tiger',
* ],
* ],
* ];
* echo Arrays::getNested($array, 'db.login.username');
* </pre>
* <br />
* Output:
* <pre>
* scott
* </pre>
*
* @param array $array The array to traverse.
* @param string $delimitedKey A string of keys to traverse into the array.
* @param string $delimiter A string specifiying how the keys are delimited. The default is '.'.
*
* @return mixed The value at the inner most key or null if a key does not exist.
*/
final public static function getNested(array $array, $delimitedKey, $delimiter = '.')
{
$pointer = $array;
foreach (explode($delimiter, $delimitedKey) as $key) {
if (is_array($pointer) && array_key_exists($key, $pointer)) {
$pointer = $pointer[$key];
continue;
}

return null;
}

return $pointer;
}
}
28 changes: 28 additions & 0 deletions tests/ArraysTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -787,4 +787,32 @@ public function nullifyEmptyStringsEmptyArray()
A::nullifyEmptyStrings($array);
$this->assertSame([], $array);
}

/**
* Verify basic functionality of getNested.
*
* @test
* @covers ::getNested
*
* @return void
*/
public function getNested()
{
$array = ['db' => ['host' => 'localhost', 'login' => [ 'username' => 'scott', 'password' => 'tiger']]];
$this->assertSame('scott', A::getNested($array, 'db.login.username'));
}

/**
* Verify behavior when the given delimitedKey does not exist in the given array.
*
* @test
* @covers ::getNested
*
* @return void
*/
public function getNestedPathNotFound()
{
$array = ['db' => ['host' => 'localhost', 'login' => [ 'username' => 'scott', 'password' => 'tiger']]];
$this->assertNull(A::getNested($array, 'db.notfound.username'));
}
}

0 comments on commit bd9114b

Please sign in to comment.