MicroFrameWork/app/controllers/MenuController.php
2024-08-30 16:14:31 +03:00

106 lines
2.6 KiB
PHP

<?php
namespace app\controllers;
use app\helpers\Debug;
use app\models\forms\CreateMenuForm;
use app\services\MenuService;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\Controller;
use kernel\models\Menu;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
class MenuController extends Controller
{
protected function init(): void
{
$this->cgView->viewPath = ROOT_DIR . "/views/admin/";
$this->cgView->layout = "layouts/main.php";
}
public function actionCreate(): void
{
$this->cgView->render("menu/form.php");
}
#[NoReturn] public function actionAdd(): void
{
$menuForm = new CreateMenuForm();
$menuService = new MenuService();
$menuForm->load($_REQUEST);
if ($menuForm->validate()){
$menuItem = $menuService->create($menuForm);
if ($menuItem){
$this->redirect("/admin/menu/" . $menuItem->id);
}
}
$this->redirect("/admin/menu/create");
}
/**
* @throws Exception
*/
public function actionIndex($page_number = 1): void
{
$this->cgView->render("menu/index.php", ['page_number' => $page_number]);
}
/**
* @throws Exception
*/
public function actionView($id): void
{
$menuItem = Menu::find($id);
if (!$menuItem){
throw new Exception(message: "The menu item not found");
}
$this->cgView->render("menu/view.php", ['menu' => $menuItem]);
}
/**
* @throws RuntimeError
* @throws SyntaxError
* @throws LoaderError|Exception
*/
public function actionUpdate($id): void
{
$model = Menu::find($id);
if (!$model){
throw new Exception(message: "The menu item not found");
}
$this->cgView->render("menu/form.php", ['model' => $model]);
}
/**
* @throws Exception
*/
public function actionEdit($id): void
{
$menuItem = Menu::find($id);
if (!$menuItem){
throw new Exception(message: "The menu item not found");
}
$menuForm = new CreateMenuForm();
$menuService = new MenuService();
$menuForm->load($_REQUEST);
if ($menuForm->validate()){
$menuItem = $menuService->update($menuForm, $menuItem);
if ($menuItem){
$this->redirect("/admin/menu/" . $menuItem->id);
}
}
$this->redirect("/admin/menu/update/" . $id);
}
#[NoReturn] public function actionDelete($id): void
{
Menu::find($id)->delete();
$this->redirect("/admin/menu/");
}
}