model::all()); } /** * Store a newly created resource in storage. */ public function store(Request $request): JsonResponse|Resource { $instance = new $this->model(); $instance->fill($request->all()); $created = $instance->save(); return $created ? new Resource($instance) : $this->error(Response::HTTP_INTERNAL_SERVER_ERROR, __('Impossibile creare la risorsa')); } /** * Display the specified resource. */ public function show(int $id): Resource|JsonResponse { $instance = $this->model::find($id); if (!assert($instance instanceof Model)) { return $this->error(Response::HTTP_NOT_FOUND, __('Risorsa non trovata.')); } return new Resource($instance); } /** * Update the specified resource in storage. */ public function update(Request $request, int $id): Resource|JsonResponse { $instance = $this->model::find($id); if (!assert($instance instanceof Model)) { return $this->error(Response::HTTP_NOT_FOUND, __('Risorsa non trovata.')); } $instance->fill($request->all()); $updated = $instance->save(); return $updated ? new Resource($instance) : $this->error(Response::HTTP_INTERNAL_SERVER_ERROR, __('Impossibile salvare le modifiche')); } /** * Remove the specified resource from storage. */ public function destroy(int $id): Response|JsonResponse { $instance = $this->model::find($id); if (!assert($instance instanceof Model)) { return $this->error(Response::HTTP_NOT_FOUND, __('Risorsa non trovata.')); } $deleted = $instance->delete(); return $deleted ? response()->noContent() : $this->error(Response::HTTP_INTERNAL_SERVER_ERROR, __('Impossibile eliminare la risorsa')); } /** @noinspection PhpSameParameterValueInspection */ private function error(int $status, string $title, ?string $detail = null): JsonResponse { return response()->json([ 'errors' => [ [ 'status' => $status, 'title' => $title, 'detail' => $detail, ], ], ], Response::HTTP_INTERNAL_SERVER_ERROR); } }