Files
shopit-back/app/Domains/Prop/Resources/PropValueResource.php

51 lines
1.3 KiB
PHP

<?php
namespace App\Domains\Prop\Resources;
use App\Domains\Prop\Concerns\Propable;
use App\Domains\Prop\Models\ModelPropValue;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use InvalidArgumentException;
/**
* @mixin ModelPropValue
*/
class PropValueResource extends JsonResource
{
/**
* @param iterable<ModelPropValue> $propValues
* @return array<string, mixed>
*/
public static function collapsed(iterable $propValues): array
{
return collect($propValues)
->mapWithKeys(fn (ModelPropValue $propValue) => [
$propValue->prop->codigo => $propValue->value,
])
->all();
}
/**
* @return array<string, mixed>
*/
public static function collapsedFromPropable(object $model): array
{
if (! in_array(Propable::class, class_uses_recursive($model), true)) {
throw new InvalidArgumentException('The given model must use the Propable trait.');
}
return static::collapsed(
$model->propValues()->with('prop')->get(),
);
}
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [$this->prop->codigo => $this->value];
}
}