From 8d7c2a30b5499b192dbc827a98a05044e1405387 Mon Sep 17 00:00:00 2001 From: aqibmehmood Date: Tue, 6 Aug 2024 13:35:26 +0500 Subject: [PATCH] add method to data_fetch get data using dot notation data_get() reproduce issue in some case --- src/Illuminate/Collections/helpers.php | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Illuminate/Collections/helpers.php b/src/Illuminate/Collections/helpers.php index 4150c38ef621..603cf3fbf265 100644 --- a/src/Illuminate/Collections/helpers.php +++ b/src/Illuminate/Collections/helpers.php @@ -95,7 +95,37 @@ function data_get($target, $key, $default = null) return $target; } } +/** + * Get an item from an array or object using "dot" notation. + * + * @param mixed $target + * @param string|array|int|null $key + * @param mixed $default + * @return mixed + */ +function data_fetch(mixed $target, string|array|int|null $key, mixed $default = null, bool $trim = false): mixed +{ + if (is_null($key)) { + return $default; + } + + $key = is_array($key) ? $key : [$key]; + $segment = array_shift($key); + + if (Arr::accessible($target) && Arr::exists($target, $segment)) { + $target = $target[$segment]; + } elseif (is_object($target) && isset($target->{$segment})) { + $target = $target->{$segment}; + } else { + return $default; + } + if ($key) { + return data_fetch($target, $key, $default); // recursive call + } else { + return ($trim) ? trim($target) : $target; + } +} if (! function_exists('data_set')) { /** * Set an item on an array or object using dot notation.