Skip to content

Commit c422d73

Browse files
committed
optimize
1 parent 667e740 commit c422d73

3 files changed

Lines changed: 48 additions & 6 deletions

File tree

system/Helpers/Array/ArrayHelper.php

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,22 @@ public static function dotSearch(string $index, array $array)
5050
*/
5151
private static function convertToArray(string $index): array
5252
{
53+
$trimmed = rtrim($index, '* ');
54+
55+
if ($trimmed === '') {
56+
return [];
57+
}
58+
59+
// Fast path: no escaped dots, skip the regex entirely.
60+
if (! str_contains($trimmed, '\\.')) {
61+
return array_values(array_filter(
62+
explode('.', $trimmed),
63+
static fn ($s): bool => $s !== '',
64+
));
65+
}
66+
5367
// See https://regex101.com/r/44Ipql/1
54-
$segments = preg_split(
55-
'/(?<!\\\\)\./',
56-
rtrim($index, '* '),
57-
0,
58-
PREG_SPLIT_NO_EMPTY,
59-
);
68+
$segments = preg_split('/(?<!\\\\)\./', $trimmed, 0, PREG_SPLIT_NO_EMPTY);
6069

6170
return array_map(
6271
static fn ($key): string => str_replace('\.', '.', $key),

tests/system/Helpers/Array/ArrayHelperDotModifyTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,16 @@ public static function provideDotKeyExists(): iterable
9696
'array' => ['user' => ['code' => '0']],
9797
'expected' => true,
9898
],
99+
'escaped dot in key' => [
100+
'index' => 'config.api\.version',
101+
'array' => ['config' => ['api.version' => 'v1']],
102+
'expected' => true,
103+
],
104+
'escaped dot key does not exist' => [
105+
'index' => 'config.api\.version',
106+
'array' => ['config' => ['api' => ['version' => 'v1']]],
107+
'expected' => false,
108+
],
99109
];
100110
}
101111

@@ -403,6 +413,24 @@ public function testDotExceptSupportsEndingWildcard(): void
403413
$this->assertSame($expected, ArrayHelper::dotExcept($array, 'user.*'));
404414
}
405415

416+
public function testDotExceptWithEscapedDotKey(): void
417+
{
418+
$array = [
419+
'config' => [
420+
'api.version' => 'v1',
421+
'region' => 'eu',
422+
],
423+
];
424+
425+
$expected = [
426+
'config' => [
427+
'region' => 'eu',
428+
],
429+
];
430+
431+
$this->assertSame($expected, ArrayHelper::dotExcept($array, 'config.api\.version'));
432+
}
433+
406434
public function testDotOnlyWithSingleWildcardReturnsWholeArray(): void
407435
{
408436
$array = [

tests/system/Helpers/ArrayHelperTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,11 @@ public static function provideDotArrayHas(): iterable
480480
'data' => ['user' => ['score' => 0]],
481481
'expected' => true,
482482
],
483+
'escaped dot in key' => [
484+
'index' => 'config.api\.version',
485+
'data' => ['config' => ['api.version' => 'v1']],
486+
'expected' => true,
487+
],
483488
];
484489
}
485490

0 commit comments

Comments
 (0)