MicroFrameWork/kernel/modules/post/controllers/PostController.php
2024-10-17 14:55:00 +03:00

108 lines
2.7 KiB
PHP

<?php
namespace kernel\modules\post\controllers;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\modules\post\models\forms\CreatePostForm;
use kernel\modules\post\models\Post;
use kernel\modules\post\service\PostService;
class PostController extends AdminController
{
private PostService $postService;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = KERNEL_MODULES_DIR . "/post/views/";
$this->postService = new PostService();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
#[NoReturn] public function actionAdd(): void
{
$postForm = new CreatePostForm();
$postForm->load($_REQUEST);
if ($postForm->validate()) {
$post = $this->postService->create($postForm);
if ($post) {
$this->redirect("/admin/post/" . $post->id);
}
}
$this->redirect("/admin/post/create");
}
/**
* @throws Exception
*/
public function actionIndex(int $page_number = 1): void
{
$this->cgView->render("index.php", ['page_number' => $page_number]);
}
/**
* @throws Exception
*/
public function actionView(int $id): void
{
$content = Post::find($id);
if (!$content){
throw new Exception(message: "The post not found");
}
$this->cgView->render("view.php", ['content' => $content]);
}
/**
* @throws Exception
*/
public function actionUpdate(int $id): void
{
$model = Post::find($id);
if (!$model){
throw new Exception(message: "The post not found");
}
$this->cgView->render("form.php", ['model' => $model]);
}
/**
* @throws Exception
*/
public function actionEdit(int $id): void
{
$post = Post::find($id);
if (!$post){
throw new Exception(message: "The post not found");
}
$postForm = new CreatePostForm();
$postForm->load($_REQUEST);
if ($postForm->validate()) {
$post = $this->postService->update($postForm, $post);
if ($post) {
$this->redirect("/admin/post/" . $post->id);
}
}
$this->redirect("/admin/post/update/" . $id);
}
/**
* @throws Exception
*/
#[NoReturn] public function actionDelete(int $id): void
{
$post = Post::find($id)->first();
if (!$post){
throw new Exception(message: "The post not found");
}
$post->delete();
$this->redirect("/admin/post/");
}
}