MicroFrameWork/kernel/RestController.php

121 lines
2.8 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 16:13:46 +03:00
#[NoReturn] public function actionStore(): void
2024-10-07 15:38:23 +03:00
{
$request = new Request();
$data = $request->post();
2024-10-07 16:13:46 +03:00
foreach ($this->model->getFillable() as $item){
$this->model->{$item} = $data[$item] ?? null;
}
$this->model->save();
$this->renderApi($this->model->toArray());
2024-10-07 15:38:23 +03:00
}
2024-10-07 16:57:26 +03:00
#[NoReturn] public function actionEdit(int $id): void
{
$request = new Request();
$data = $request->post();
$model = $this->model->where('id', $id)->first();
foreach ($model->getFillable() as $item){
2024-12-16 13:14:28 +03:00
if (!empty($data[$item])){
$model->{$item} = $data[$item] ?? null;
}
2024-10-07 16:57:26 +03:00
}
$model->save();
$this->renderApi($model->toArray());
}
2024-10-22 11:09:35 +03:00
#[NoReturn] public function returnError(int $code): void
{
http_response_code($code);
die('Forbidden');
}
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();
}
2024-10-22 11:09:35 +03:00
2024-09-26 14:47:13 +03:00
}