feat(misc): add reusable response and options helpers

This commit is contained in:
Fabian Wagner 2026-04-17 09:50:33 +02:00
parent 7bf997d798
commit e2c663522c
1 changed files with 91 additions and 10 deletions

View File

@ -7,23 +7,104 @@ use Illuminate\Support\Facades\Log;
class MiscService class MiscService
{ {
/**
* Build a standard response payload envelope.
*/
public static function response(
mixed $data = null,
array $meta = []
): array {
return [
'data' => $data,
'meta' => $meta,
];
}
/**
* Resolve a controller payload to a normalized options array.
*
* Supported payload shapes:
* - ['options' => [...]]
* - [...] (already flat)
*/
public static function resolveOptions(
array $payload,
array $defaults = []
): array {
$options = is_array($payload['options'] ?? null)
? $payload['options']
: $payload;
return array_merge($defaults, $options);
}
/**
* Read an option value using camelCase or snake_case fallback.
*/
public static function option(
array $options,
string $key,
mixed $default = null
): mixed {
if (array_key_exists($key, $options)) {
return $options[$key];
}
$snake = str($key)->snake()->toString();
if (array_key_exists($snake, $options)) {
return $options[$snake];
}
$camel = str($key)->camel()->toString();
if (array_key_exists($camel, $options)) {
return $options[$camel];
}
return $default;
}
/**
* Build pagination metadata in a consistent format.
*/
public static function paginationMeta(
$paginated,
array $options = [],
array $meta = []
): array {
$data = $paginated->toArray();
$base = [
'from' => @$data['from'],
'to' => @$data['to'],
'total' => @$data['total'],
'last_page' => @$data['last_page'],
'current_page' => @$data['current_page'],
'options' => (object) $options,
];
if ($meta) {
$base = array_merge($base, $meta);
}
return $base;
}
public static function asPaginated( public static function asPaginated(
$paginated, $paginated,
$resource_class, $resource_class,
array $meta = [] array $meta = [],
?array $options = null
) { ) {
$data = $paginated->toArray(); $resolvedOptions = $options;
if ($resolvedOptions === null) {
$resolvedOptions = is_array(request('options'))
? request('options')
: [];
}
$payload = [ $payload = [
'data' => $resource_class::collection($paginated), 'data' => $resource_class::collection($paginated),
'meta' => [ 'meta' => self::paginationMeta($paginated, $resolvedOptions),
'from' => @$data['from'],
'to' => @$data['to'],
'total' => @$data['total'],
'last_page' => @$data['last_page'],
'current_page' => @$data['current_page'],
'options' => (object) request('options'),
],
]; ];
if ($meta) { if ($meta) {