rest and post

This commit is contained in:
2025-01-09 16:27:34 +03:00
parent 1a54003030
commit dd231b0c07
5 changed files with 90 additions and 13 deletions

View File

@ -17,13 +17,32 @@ class RestController
return [];
}
protected function filters(): array
{
return [];
}
#[NoReturn] public function actionIndex(): void
{
$request = new Request();
$get = $request->get();
$page = $request->get('page') ?? 1;
$perPage = $request->get('per_page') ?? 10;
$query = $this->model->query();
if ($this->filters()) {
foreach ($this->filters() as $filter){
if (key_exists($filter, $get)){
if (is_numeric($get[$filter])){
$query->where($filter, $get[$filter]);
}
elseif (is_string($get[$filter])){
$query->where($filter,'like', '%' . $get[$filter] . '%');
}
}
}
}
if ($page > 1) {
$query->skip(($page - 1) * $perPage)->take($perPage);
} else {
@ -31,7 +50,7 @@ class RestController
}
$expand = $this->expand();
$expandParams = explode( ",", $request->get('expand') ?? "");
$expandParams = explode(",", $request->get('expand') ?? "");
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand) {
$res = $query->get()->load($finalExpand)->toArray();
@ -46,14 +65,14 @@ class RestController
{
$expand = $this->expand();
$request = new Request();
$expandParams = explode( ",", $request->get('expand') ?? "");
$expandParams = explode(",", $request->get('expand') ?? "");
$model = $this->model->where("id", $id)->first();
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand){
if ($finalExpand) {
$model->load($finalExpand);
}
$res = [];
if ($model){
if ($model) {
$res = $model->toArray();
}
@ -64,7 +83,7 @@ class RestController
{
$model = $this->model->where("id", $id)->first();
$res = [];
if ($model){
if ($model) {
$res = $model->toArray();
}
@ -78,7 +97,7 @@ class RestController
{
$request = new Request();
$data = $request->post();
foreach ($this->model->getFillable() as $item){
foreach ($this->model->getFillable() as $item) {
$this->model->{$item} = $data[$item] ?? null;
}
$this->model->save();
@ -93,8 +112,8 @@ class RestController
$model = $this->model->where('id', $id)->first();
foreach ($model->getFillable() as $item){
if (!empty($data[$item])){
foreach ($model->getFillable() as $item) {
if (!empty($data[$item])) {
$model->{$item} = $data[$item] ?? null;
}
}
@ -117,5 +136,4 @@ class RestController
}
}