Files
memefast/app/Helpers/Global/cast_helpers.php
2025-06-13 09:44:18 +08:00

94 lines
2.5 KiB
PHP

<?php
use Vinkla\Hashids\Facades\Hashids;
if (! function_exists('array_to_object_2025')) {
/**
* A magic function that turns all nested array into nested objects. Calling it with no parameter would result in a empty object.
*
* @param mixed $array The array to be recursively casted into an object.
* @return \stdClass|null Returns null if the given parameter is not either an array or an object.
*/
function array_to_object_2025($array = []): ?stdClass
{
if (is_object($array)) {
return $array;
}
if (! is_array($array)) {
return null;
}
$object = new \stdClass;
if (! isset($array) || empty($array)) {
return $object;
}
foreach ($array as $k => $v) {
if (mb_strlen($k)) {
if (is_array($v)) {
if (array_is_assoc($v)) {
// Convert associative arrays to objects
$object->{$k} = array_to_object_2025($v);
} else {
// For indexed arrays, keep them as arrays but process their elements
$object->{$k} = [];
foreach ($v as $idx => $item) {
if (is_array($item)) {
$object->{$k}[$idx] = array_to_object_2025($item);
} else {
$object->{$k}[$idx] = $item;
}
}
}
} else {
$object->{$k} = $v;
}
}
}
return $object;
}
}
if (! function_exists('array_is_assoc')) {
/**
* Determines whether or not an array is an associative array.
*
* @param array $array The array to be evaluated.
*/
function array_is_assoc($array): bool
{
if (! is_array($array)) {
return false;
}
if ($array === []) {
return false;
}
return array_keys($array) !== range(0, count($array) - 1);
}
}
if (! function_exists('hashids_encode')) {
function hashids_encode($id)
{
return Hashids::encode($id);
}
}
if (! function_exists('hashids_decode')) {
function hashids_decode($string)
{
$arr = Hashids::decode($string);
if (count($arr) > 0) {
return $arr[0];
}
return null;
}
}