Add initial Code
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
namespace App\Support;
|
||||
|
||||
class ApiDataTransformer
|
||||
{
|
||||
/**
|
||||
* Convert array keys from snake_case to camelCase recursively
|
||||
*/
|
||||
public static function snakeToCamel(array $data): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
$camelKey = self::convertSnakeToCamel($key);
|
||||
|
||||
if (is_array($value)) {
|
||||
$result[$camelKey] = self::snakeToCamel($value);
|
||||
} elseif (is_object($value)) {
|
||||
$result[$camelKey] = self::snakeToCamel((array)$value);
|
||||
} else {
|
||||
$result[$camelKey] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert array keys from camelCase to snake_case recursively
|
||||
*/
|
||||
public static function camelToSnake(array $data): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
$snakeKey = self::convertCamelToSnake($key);
|
||||
|
||||
if (is_array($value)) {
|
||||
$result[$snakeKey] = self::camelToSnake($value);
|
||||
} elseif (is_object($value)) {
|
||||
$result[$snakeKey] = self::camelToSnake((array)$value);
|
||||
} else {
|
||||
$result[$snakeKey] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a single string from snake_case to camelCase
|
||||
*/
|
||||
protected static function convertSnakeToCamel(string $string): string
|
||||
{
|
||||
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $string))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a single string from camelCase to snake_case
|
||||
*/
|
||||
protected static function convertCamelToSnake(string $string): string
|
||||
{
|
||||
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $string));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user