Skip to content
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

Feature: Escaping array dot notation #4588

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 5 additions & 1 deletion system/Helpers/array_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@
*/
function dot_array_search(string $index, array $array)
{
$segments = explode('.', rtrim(rtrim($index, '* '), '.'));
$segments = preg_split('/(?<!\\\)\./', rtrim($index, '* '), 0, PREG_SPLIT_NO_EMPTY);
iRedds marked this conversation as resolved.
Show resolved Hide resolved

$segments = array_map(function ($key) {
iRedds marked this conversation as resolved.
Show resolved Hide resolved
return str_replace('\.', '.', $key);
}, $segments);

return _array_search_dot($segments, $array);
}
Expand Down
15 changes: 15 additions & 0 deletions tests/system/Helpers/ArrayHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ public function testArrayDotTooManyLevels()
$this->assertEquals(23, dot_array_search('foo.bar.baz', $data));
}

public function testArrayDotEscape()
{
$data = [
'foo' => [
'bar.baz' => 23,
],
'foo.bar' => [
'baz' => 42,
],
];

$this->assertEquals(23, dot_array_search('foo.bar\.baz', $data));
$this->assertEquals(42, dot_array_search('foo\.bar.baz', $data));
}

public function testArrayDotReturnNullEmptyArray()
{
$data = [];
Expand Down
17 changes: 17 additions & 0 deletions user_guide_src/source/helpers/array_helper.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,23 @@ The following functions are available:
// Returns: 23
$baz = dot_array_search('foo.*.baz', $data);

If the array key contains a dot, then the key can be escaped with a backslash::
$data = [
iRedds marked this conversation as resolved.
Show resolved Hide resolved
'foo' => [
'bar.baz' => 23
],
'foo.bar' => [
'baz' => 43
],

];

// Returns: 23
$barBaz = dot_array_search('foo.bar\.baz', $data);
// Returns: 42
$fooBar = dot_array_search('foo\.bar.baz', $data);


.. php:function:: array_deep_search($key, array $array)

:param mixed $key: The target key
Expand Down