query->get('page') ?? 1); $perPage = (int) ($request->query->get('per_page') ?? 25); $sortBy = $request->query->get('sort_by'); $sortDir = $request->query->get('sort_dir') ?? 'asc'; $search = $request->query->get('search'); // Build filters $filters = []; if ($search) { $filters['search'] = $search; } // Fetch data from repository $data = $repository->findAll($filters); // Apply sorting if requested if ($sortBy && method_exists($repository, 'sortBy')) { $data = $repository->sortBy($data, $sortBy, $sortDir); } // Apply pagination $total = count($data); $offset = ($page - 1) * $perPage; $paginatedData = array_slice($data, $offset, $perPage); // Convert to arrays $items = array_map( fn($item) => method_exists($item, 'toArray') ? $item->toArray() : (array) $item, $paginatedData ); return new JsonResult([ 'success' => true, 'data' => $items, 'pagination' => [ 'page' => $page, 'per_page' => $perPage, 'total' => $total, 'pages' => (int) ceil($total / $perPage), ], ]); } public function handleGet( string $id, mixed $repository ): JsonResult { $item = $repository->findById($id); if ($item === null) { return new JsonResult([ 'success' => false, 'error' => 'Resource not found', ], Status::NOT_FOUND); } $data = method_exists($item, 'toArray') ? $item->toArray() : (array) $item; return new JsonResult([ 'success' => true, 'data' => $data, ]); } public function handleCreate( HttpRequest $request, mixed $repository ): JsonResult { $data = $request->parsedBody->toArray(); try { $item = $repository->create($data); $responseData = method_exists($item, 'toArray') ? $item->toArray() : (array) $item; return new JsonResult([ 'success' => true, 'data' => $responseData, 'message' => 'Resource created successfully', ], Status::CREATED); } catch (\Exception $e) { return new JsonResult([ 'success' => false, 'error' => $e->getMessage(), ], Status::BAD_REQUEST); } } public function handleUpdate( string $id, HttpRequest $request, mixed $repository ): JsonResult { $data = $request->parsedBody->toArray(); try { $item = $repository->update($id, $data); if ($item === null) { return new JsonResult([ 'success' => false, 'error' => 'Resource not found', ], Status::NOT_FOUND); } $responseData = method_exists($item, 'toArray') ? $item->toArray() : (array) $item; return new JsonResult([ 'success' => true, 'data' => $responseData, 'message' => 'Resource updated successfully', ]); } catch (\Exception $e) { return new JsonResult([ 'success' => false, 'error' => $e->getMessage(), ], Status::BAD_REQUEST); } } public function handleDelete( string $id, mixed $repository ): JsonResult { try { $deleted = $repository->delete($id); if (!$deleted) { return new JsonResult([ 'success' => false, 'error' => 'Resource not found', ], Status::NOT_FOUND); } return new JsonResult([ 'success' => true, 'message' => 'Resource deleted successfully', ]); } catch (\Exception $e) { return new JsonResult([ 'success' => false, 'error' => $e->getMessage(), ], Status::BAD_REQUEST); } } }