igfs/kernel/RestController.php

97 lines
2.3 KiB
PHP
Raw Normal View History

2024-09-26 14:47:13 +03:00
<?php
namespace kernel;
use Illuminate\Database\Eloquent\Model;
use JetBrains\PhpStorm\NoReturn;
use kernel\helpers\Debug;
class RestController
{
protected Model $model;
2024-10-07 11:31:16 +03:00
protected function expand(): array
{
return [];
}
2024-09-26 14:47:13 +03:00
#[NoReturn] public function actionIndex(): void
{
$request = new Request();
$page = $request->get('page') ?? 1;
$perPage = $request->get('per_page') ?? 10;
$query = $this->model->query();
2024-10-07 15:38:23 +03:00
2024-09-26 14:47:13 +03:00
if ($page > 1) {
$query->skip(($page - 1) * $perPage)->take($perPage);
} else {
$query->take($perPage);
}
2024-10-07 15:38:23 +03:00
$expand = $this->expand();
$expandParams = explode( ",", $request->get('expand') ?? "");
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand) {
$res = $query->get()->load($finalExpand)->toArray();
} else {
$res = $query->get()->toArray();
}
2024-09-26 14:47:13 +03:00
$this->renderApi($res);
}
#[NoReturn] public function actionView($id): void
{
2024-10-07 11:31:16 +03:00
$expand = $this->expand();
2024-10-07 11:54:10 +03:00
$request = new Request();
$expandParams = explode( ",", $request->get('expand') ?? "");
2024-09-26 14:47:13 +03:00
$model = $this->model->where("id", $id)->first();
2024-10-07 11:54:10 +03:00
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand){
$model->load($finalExpand);
2024-10-07 11:31:16 +03:00
}
2024-09-26 14:47:13 +03:00
$res = [];
if ($model){
$res = $model->toArray();
}
$this->renderApi($res);
}
#[NoReturn] public function actionDelete($id): void
{
$model = $this->model->where("id", $id)->first();
$res = [];
if ($model){
$res = $model->toArray();
}
$model->delete();
$this->renderApi($res);
}
2024-10-07 15:38:23 +03:00
#[NoReturn] public function actionCreate(): void
{
$request = new Request();
$data = $request->post();
$data = [
'title' => 'title'
];
Debug::prn($data);
$model = $this->model;
Debug::prn($model->toArray());
$model->save($data);
}
2024-09-26 14:47:13 +03:00
#[NoReturn] protected function renderApi(array $data): void
{
header("Content-Type: application/json");
echo json_encode($data);
exit();
}
}