Skip to content

Commit 97738f7

Browse files
authored
Prevent infinite loop on array_first, array_last, str_contains (#37)
* prevent infinite loop on array_first, array_last, str_contains * add deprecation notes
1 parent bc28464 commit 97738f7

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

src/helpers.php

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,14 +76,31 @@ function array_except($array, $keys)
7676
/**
7777
* Return the first element in an array passing a given truth test.
7878
*
79+
* @deprecated A native function with the same name was introduced in PHP 8.5.
80+
* Use Illuminate\Support\Arr::first to keep functionality
81+
*
7982
* @param array $array
8083
* @param callable|null $callback
8184
* @param mixed $default
8285
* @return mixed
8386
*/
8487
function array_first($array, ?callable $callback = null, $default = null)
8588
{
86-
return Arr::first($array, $callback, $default);
89+
if (is_null($callback)) {
90+
if (empty($array)) {
91+
return value($default);
92+
}
93+
94+
foreach ($array as $item) {
95+
return $item;
96+
}
97+
98+
return value($default);
99+
}
100+
101+
$key = array_find_key($array, $callback);
102+
103+
return $key !== null ? $array[$key] : value($default);
87104
}
88105
}
89106

@@ -148,14 +165,21 @@ function array_has($array, $keys)
148165
/**
149166
* Return the last element in an array passing a given truth test.
150167
*
168+
* @deprecated A native function with the same name was introduced in PHP 8.5.
169+
* Use Illuminate\Support\Arr::last to keep functionality
170+
*
151171
* @param array $array
152172
* @param callable|null $callback
153173
* @param mixed $default
154174
* @return mixed
155175
*/
156176
function array_last($array, ?callable $callback = null, $default = null)
157177
{
158-
return Arr::last($array, $callback, $default);
178+
if (is_null($callback)) {
179+
return empty($array) ? value($default) : end($array);
180+
}
181+
182+
return Arr::first(array_reverse($array, true), $callback, $default);
159183
}
160184
}
161185

@@ -403,13 +427,30 @@ function str_before($subject, $search)
403427
/**
404428
* Determine if a given string contains a given substring.
405429
*
430+
* @deprecated A native function with the same name was introduced in PHP 8.0.
431+
* Use Illuminate\Support\Str::contains to keep functionality
432+
*
406433
* @param string $haystack
407434
* @param string|array $needles
408435
* @return bool
409436
*/
410437
function str_contains($haystack, $needles)
411438
{
412-
return Str::contains($haystack, $needles);
439+
if (is_null($haystack)) {
440+
return false;
441+
}
442+
443+
if (! is_iterable($needles)) {
444+
$needles = (array) $needles;
445+
}
446+
447+
foreach ($needles as $needle) {
448+
if ($needle !== '' && strpos($haystack, $needle) !== false) {
449+
return true;
450+
}
451+
}
452+
453+
return false;
413454
}
414455
}
415456

0 commit comments

Comments
 (0)