Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
`get_deep_value`, a version of `_.get` for PHP
<?php
require_once( 'get-deep-value.php' );
/**
* @runTestsInSeparateProcess
*/
class Get_Deep_Value_Test extends PHPUnit_Framework_TestCase {
use Codeception\Specify;
public function test_get_deep_value() {
$this->specify( 'returns null if the haystack is empty', function() {
$haystack = [];
$key_path = [ 'one', 'two' ];
$actual = Get_Deep_Value::get_deep_value( $haystack, $key_path );
$expected = null;
expect( $actual )->equals( $expected );
} );
$this->specify( 'returns null if the haystack does not contain the first key', function() {
$haystack = [ 'three' => 'foo' ];
$key_path = [ 'one', 'two' ];
$actual = Get_Deep_Value::get_deep_value( $haystack, $key_path );
$expected = null;
expect( $actual )->equals( $expected );
} );
$this->specify( 'returns null if the haystack does not contain the second key', function() {
$haystack = [ 'one' => [ 'three' => 'foo' ] ];
$key_path = [ 'one', 'two' ];
$actual = Get_Deep_Value::get_deep_value( $haystack, $key_path );
$expected = null;
expect( $actual )->equals( $expected );
} );
$this->specify( 'returns the second value if the haystack does contain the second key', function() {
$haystack = [ 'one' => [ 'two' => 'foo' ] ];
$key_path = [ 'one', 'two' ];
$actual = Get_Deep_Value::get_deep_value( $haystack, $key_path );
$expected = 'foo';
expect( $actual )->equals( $expected );
} );
$this->specify( 'returns the third value if the haystack does contain the third key', function() {
$haystack = [ 'one' => [ 'two' => [ 'four' => 'bar', 'three' => 'foo' ] ] ];
$key_path = [ 'one', 'two', 'three' ];
$actual = Get_Deep_Value::get_deep_value( $haystack, $key_path );
$expected = 'foo';
expect( $actual )->equals( $expected );
} );
}
}
<?php
class Get_Deep_Value {
/**
* Return a deeply nested value of an array if it exists
*
* @param array $haystack The associative array to search
* @param array $key_path An ordered set of keys in the $haystack
*
* @return mixed|null The value last element of the nested array in the key path
*/
public static function get_deep_value( $haystack, $key_path ) {
$key = array_shift( $key_path );
if ( ! isset( $haystack[ $key ] ) ) {
return null;
}
if ( empty( $key_path ) ) {
return $haystack[ $key ];
}
return self::get_deep_value( $haystack[ $key ], $key_path );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment