| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentBoards\Framework\Support; |
| 4 |
|
| 5 |
use stdClass; |
| 6 |
use ArrayAccess; |
| 7 |
|
| 8 |
class StdObject |
| 9 |
{ |
| 10 |
/** |
| 11 |
* Creates an stdClass from an array |
| 12 |
* |
| 13 |
* @param array $array |
| 14 |
* @return stdClass |
| 15 |
*/ |
| 16 |
public static function create(array $array) |
| 17 |
{ |
| 18 |
$object = new stdClass; |
| 19 |
|
| 20 |
foreach ($array as $key => $value) { |
| 21 |
if (is_array($value)) { |
| 22 |
$object->{$key} = call_user_func(__METHOD__, $value); |
| 23 |
} else { |
| 24 |
$object->{$key} = $value; |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
return $object; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Get an item from an object using "dot" notation. |
| 33 |
* |
| 34 |
* @template TValue of object |
| 35 |
* |
| 36 |
* @param TValue $object |
| 37 |
* @param string|null $key |
| 38 |
* @param mixed $default |
| 39 |
* @return ($key is empty ? TValue : mixed) |
| 40 |
*/ |
| 41 |
public static function get($object, $key, $default = null) |
| 42 |
{ |
| 43 |
if (is_null($key) || trim($key) === '') { |
| 44 |
return $object; |
| 45 |
} |
| 46 |
|
| 47 |
foreach (explode('.', $key) as $segment) { |
| 48 |
if (is_object($object) && isset($object->{$segment})) { |
| 49 |
$object = $object->{$segment}; |
| 50 |
} elseif ( |
| 51 |
(is_array($object) || $object instanceof ArrayAccess) |
| 52 |
&& isset($object[$segment]) |
| 53 |
) { |
| 54 |
$object = $object[$segment]; |
| 55 |
} else { |
| 56 |
return $default; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
return $object; |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Transforms an stdClass to array |
| 65 |
* |
| 66 |
* @param stdClass $object |
| 67 |
* @return array |
| 68 |
*/ |
| 69 |
public static function toArray($object) |
| 70 |
{ |
| 71 |
$array = []; |
| 72 |
|
| 73 |
foreach ($object as $key => $value) { |
| 74 |
if ($value instanceof stdClass) { |
| 75 |
$array[$key] = call_user_func(__METHOD__, $value); |
| 76 |
} else { |
| 77 |
$array[$key] = $value; |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
return $array; |
| 82 |
} |
| 83 |
} |
| 84 |
|