Last active
November 4, 2021 16:48
-
-
Save kmuenkel/bebffacd94548ddd138d48d44b5a070d to your computer and use it in GitHub Desktop.
Laravel Collection Macro for a dot-notation version of 'get' with wildcard support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Collection::macro('getDot', function ($index, $default = null) { | |
/** @var Collection $this */ | |
$indexes = preg_split('~(?<!\\\)\.~', $index); | |
$indexes = array_map(function ($index) { | |
return preg_replace('~\\\.~', '.', $index); | |
}, $indexes); | |
$item = collect($this->all()); | |
foreach ($indexes as $index) { | |
if (!($item instanceof Collection) || (strpos($index, '*') === false && !$item->has($index))) { | |
return $default; | |
} | |
if (strpos($index, '*') !== false) { | |
return $item->filter(function ($value, $key) use ($index) { | |
return fnmatch($index, $key); | |
}); | |
} | |
$item = $item->get($index); | |
$item = (is_array($item) || $item instanceof stdClass) ? collect($item) : $item; | |
} | |
return $item; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment