crud menu

This commit is contained in:
Билай Станислав 2024-08-30 16:14:31 +03:00
parent 5b4676a4c0
commit c325b156bd
28 changed files with 442 additions and 132 deletions

View File

@ -0,0 +1,106 @@
<?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/");
}
}

View File

@ -30,18 +30,12 @@ class PostController extends Controller
$postForm = new CreatePostForm(); $postForm = new CreatePostForm();
$postService = new PostService(); $postService = new PostService();
$postForm->load($_REQUEST); $postForm->load($_REQUEST);
// Debug::dd($_REQUEST);
if(UserService::check($_REQUEST['user_id'])) {
// Debug::dd(123);
if ($postForm->validate()) { if ($postForm->validate()) {
// Debug::dd($postForm);
$post = $postService->create($postForm); $post = $postService->create($postForm);
if ($post) { if ($post) {
$this->redirect("/admin/post/" . $post->id); $this->redirect("/admin/post/" . $post->id);
} }
} }
}
$this->redirect("/admin/post/create"); $this->redirect("/admin/post/create");
} }
@ -49,11 +43,9 @@ class PostController extends Controller
* @throws Exception * @throws Exception
*/ */
public function actionIndex(): void public function actionIndex($page_number = 1): void
{ {
$contents = Post::all(); $this->cgView->render("post/index.php", ['page_number' => $page_number]);
$this->cgView->render("post/index.php", ['contents' => $contents]);
} }
/** /**

View File

@ -2,31 +2,16 @@
namespace app\controllers; namespace app\controllers;
use app\foo;
use app\helpers\Debug;
use app\models\forms\CreateUserForm; use app\models\forms\CreateUserForm;
use app\models\Question; use app\models\Question;
use app\models\User; use app\models\User;
use app\services\UserService; use app\services\UserService;
use app\tables\columns\UserEditActionColumn;
use app\tables\columns\UserViewActionColumn;
use Exception; use Exception;
use http\Message;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Itguild\Tables\ListJsonTable;
use Itguild\Tables\ViewJsonTable;
use JetBrains\PhpStorm\NoReturn; use JetBrains\PhpStorm\NoReturn;
use kernel\App;
use kernel\Controller; use kernel\Controller;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\EloquentDataProvider;
use kernel\IGTabel\ListJsonTableEloquentCollection;
use kernel\IGTabel\ViewJsonTableEloquentModel;
use Twig\Error\LoaderError; use Twig\Error\LoaderError;
use Twig\Error\RuntimeError; use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError; use Twig\Error\SyntaxError;
use Twig\TwigFunction;
class UserController extends Controller{ class UserController extends Controller{
protected function init(): void protected function init(): void

View File

@ -1,47 +0,0 @@
<?php
namespace app;
class foo
{
public array $informationArray;
/**
* @param array $columns
* @param array $data
* @param string $title
* @return string|null
*/
public function createJsonArray(array $columns, array $data, string $title): ?string
{
if ($columns && $data) {
$this->informationArray = [
"meta" => [
"title" => $title,
"columns" => $columns,
"perPage" => 10,
"currentPage" => 1,
"params" =>
[
"class" => "table table-bordered",
"border" => "1"
]
],
"data" => $data
];
return $this->toJson($this->informationArray);
}
return null;
}
/**
* @param array $infArr
* @return string|null
*/
protected function toJson(array $infArr): ?string
{
if ($infArr)
return json_encode($infArr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
return null;
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace app\models\forms;
use kernel\FormModel;
class CreateMenuForm extends FormModel
{
public function rules(): array
{
return [
'parent_id' => '',
'icon_file' => '',
'icon_font' => '',
'label' => 'required|min-str-len:1|max-str-len:50',
'url' => 'required|min-str-len:1',
'status' => ''
];
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace app\services;
use app\helpers\Debug;
use kernel\FormModel;
use kernel\models\Menu;
class MenuService
{
public function create(FormModel $form_model): false|Menu
{
$model = new Menu();
$model->parent_id = $form_model->getItem('parent_id');
$model->icon_file = $form_model->getItem('icon_file');
$model->icon_font = $form_model->getItem('icon_font');
$model->label = $form_model->getItem('label');
$model->url = $form_model->getItem('url');
$model->status = $form_model->getItem('status');
if ($model->save()){
return $model;
}
return false;
}
public function update(FormModel $form_model, Menu $menuItem): false|Menu
{
$menuItem->parent_id = $form_model->getItem('parent_id');
$menuItem->icon_file = $form_model->getItem('icon_file');
$menuItem->icon_font = $form_model->getItem('icon_font');
$menuItem->label = $form_model->getItem('label');
$menuItem->url = $form_model->getItem('url');
$menuItem->status = $form_model->getItem('status');
if ($menuItem->save()){
return $menuItem;
}
return false;
}
public static function createLabelArr(): array
{
foreach (Menu::all()->toArray() as $menuItem) {
$labelArr[$menuItem['id']] = $menuItem['label'];
}
if (!empty($labelArr)) {
return $labelArr;
}
return [];
}
}

View File

@ -34,16 +34,6 @@ class UserService
return false; return false;
} }
public static function check(int $user_id): bool
{
if (User::where(['id' => $user_id])->first())
{
return true;
}
return false;
}
public static function createUsernameArr(): array public static function createUsernameArr(): array
{ {
foreach (User::all()->toArray() as $user) { foreach (User::all()->toArray() as $user) {

View File

@ -0,0 +1,17 @@
<?php
namespace app\tables\columns\menu;
use Itguild\Tables\ActionColumn\ActionColumn;
class MenuDeleteActionColumn extends ActionColumn
{
protected string $prefix = "/delete/";
public function fetch(): string
{
$link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-danger'>Удалить</a> ";
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace app\tables\columns\menu;
use Itguild\Tables\ActionColumn\ActionColumn;
class MenuEditActionColumn extends ActionColumn
{
protected string $prefix = "/update/";
public function fetch(): string
{
$link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-success'>Редактировать</a> ";
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace app\tables\columns\menu;
use Itguild\Tables\ActionColumn\ActionColumn;
class MenuViewActionColumn extends ActionColumn
{
protected string $prefix = "/";
public function fetch(): string
{
$link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-primary'>Просмотр</a> ";
}
}

View File

@ -1,6 +1,6 @@
<?php <?php
namespace app\tables\columns; namespace app\tables\columns\post;
use Itguild\Tables\ActionColumn\ActionColumn; use Itguild\Tables\ActionColumn\ActionColumn;

View File

@ -1,6 +1,6 @@
<?php <?php
namespace app\tables\columns; namespace app\tables\columns\post;
use Itguild\Tables\ActionColumn\ActionColumn; use Itguild\Tables\ActionColumn\ActionColumn;

View File

@ -1,6 +1,6 @@
<?php <?php
namespace app\tables\columns; namespace app\tables\columns\post;
use Itguild\Tables\ActionColumn\ActionColumn; use Itguild\Tables\ActionColumn\ActionColumn;

View File

@ -1,8 +1,7 @@
<?php <?php
namespace app\tables\columns; namespace app\tables\columns\user;
use app\helpers\Debug;
use Itguild\Tables\ActionColumn\ActionColumn; use Itguild\Tables\ActionColumn\ActionColumn;
class UserDeleteActionColumn extends ActionColumn class UserDeleteActionColumn extends ActionColumn

View File

@ -1,6 +1,6 @@
<?php <?php
namespace app\tables\columns; namespace app\tables\columns\user;
use Itguild\Tables\ActionColumn\ActionColumn; use Itguild\Tables\ActionColumn\ActionColumn;
@ -10,7 +10,6 @@ class UserEditActionColumn extends ActionColumn
public function fetch(): string public function fetch(): string
{ {
// $link = $this->baseUrl . $this->prefix . $this->id . $this->prefix . "update";
$link = $this->baseUrl . $this->prefix . $this->id; $link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-success'>Редактировать</a> "; return " <a href='$link' class='btn btn-success'>Редактировать</a> ";
} }

View File

@ -1,6 +1,6 @@
<?php <?php
namespace app\tables\columns; namespace app\tables\columns\user;
use Itguild\Tables\ActionColumn\ActionColumn; use Itguild\Tables\ActionColumn\ActionColumn;

View File

@ -53,7 +53,6 @@ class FormModel
} }
return false; return false;
//return $this->validator->validate($this->data, $this->rules());
} }
public function getErrors(): array public function getErrors(): array

View File

@ -5,6 +5,17 @@ namespace kernel\models;
use app\helpers\Debug; use app\helpers\Debug;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property int parent_id
* @property string icon_file
* @property string icon_font
* @property string label
* @property string url
* @property int status
* @method static find($id)
*/
class Menu extends Model class Menu extends Model
{ {
protected $table = 'menu'; protected $table = 'menu';

View File

@ -28,4 +28,14 @@ App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){
App::$collector->any("/edit/{id}", [\app\controllers\PostController::class, 'actionEdit']); App::$collector->any("/edit/{id}", [\app\controllers\PostController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\app\controllers\PostController::class, 'actionDelete']); App::$collector->get('/delete/{id}', [\app\controllers\PostController::class, 'actionDelete']);
}); });
App::$collector->group(["prefix" => "menu"], function (RouteCollector $router){
App::$collector->get('/', [\app\controllers\MenuController::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\app\controllers\MenuController::class, 'actionIndex']);
App::$collector->get('/create', [\app\controllers\MenuController::class, 'actionCreate']);
App::$collector->post("/", [\app\controllers\MenuController::class, 'actionAdd']);
App::$collector->get('/{id}', [\app\controllers\MenuController::class, 'actionView']);
App::$collector->any('/update/{id}', [\app\controllers\MenuController::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\app\controllers\MenuController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\app\controllers\MenuController::class, 'actionDelete']);
});
}); });

77
views/admin/menu/form.php Normal file
View File

@ -0,0 +1,77 @@
<?php
/**
* @var Menu $model
*/
use kernel\models\Menu;
$form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/menu/edit/" . $model->id : "/admin/menu");
$form->field(class: \itguild\forms\inputs\Select::class, name: "parent_id", params: [
'class' => "form-control",
'value' => $model->parent_id ?? ''
])
->setLabel("Родительский пункт меню")
->setOptions(\app\services\MenuService::createLabelArr())
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "icon_file", params: [
'class' => "form-control",
'value' => $model->icon_file ?? ''
])
->setLabel("Путь к иконке")
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "icon_font", params: [
'class' => "form-control",
'value' => $model->icon_font ?? ''
])
->setLabel("Иконка")
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "label", params: [
'class' => "form-control",
'value' => $model->label ?? ''
])
->setLabel("Заголовок")
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "url", params: [
'class' => "form-control",
'value' => $model->url ?? ''
])
->setLabel("URL")
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "status", params: [
'class' => "form-control",
'value' => strval($model->status) ?? '1'
])
->setLabel("Статус")
->render();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,49 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $menuItem
* @var int $page_number
*/
use app\tables\columns\menu\MenuDeleteActionColumn;
use app\tables\columns\menu\MenuEditActionColumn;
use app\tables\columns\menu\MenuViewActionColumn;
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\models\Menu;
$table = new ListEloquentTable(new EloquentDataProvider(Menu::class, [
'currentPage' => $page_number,
'perPage' => 3,
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/menu",
]));
$table->columns([
'parent_id' => (function ($data) {
if ($data == 0) return null;
return Menu::find($data)->label;
}),
'created_at' => function ($data) {
if (!$data){
return null;
}
return (new DateTimeImmutable($data))->format("d-m-Y");
},
'updated_at' => function ($data) {
if (!$data){
return null;
}
return (new DateTimeImmutable($data))->format("d-m-Y");
}
]);
$table->beforePrint(function () {
return PrimaryBtn::create("Создать", "/admin/menu/create")->fetch();
//return (new PrimaryBtn("Создать", "/admin/user/create"))->fetch();
});
$table->addAction(MenuViewActionColumn::class);
$table->addAction(MenuEditActionColumn::class);
$table->addAction(MenuDeleteActionColumn::class);
$table->create();
$table->render();

46
views/admin/menu/view.php Normal file
View File

@ -0,0 +1,46 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $menu
*/
use app\models\User;
use Itguild\EloquentTable\ViewEloquentTable;
use Itguild\EloquentTable\ViewJsonTableEloquentModel;
use kernel\IGTabel\btn\DangerBtn;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\btn\SuccessBtn;
use kernel\models\Menu;
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($menu, [
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/menu",
]));
$table->beforePrint(function () use ($menu) {
$btn = PrimaryBtn::create("Список", "/admin/menu")->fetch();
$btn .= SuccessBtn::create("Редактировать", "/admin/menu/update/" . $menu->id)->fetch();
$btn .= DangerBtn::create("Удалить", "/admin/menu/delete/" . $menu->id)->fetch();
return $btn;
});
$table->rows([
'parent_id' => (function ($data) {
if ($data == 0) return null;
return Menu::find($data)->label;
}),
'created_at' => function ($data) {
if (!$data){
return null;
}
return (new DateTimeImmutable($data))->format("d-m-Y");
},
'updated_at' => function ($data) {
if (!$data){
return null;
}
return (new DateTimeImmutable($data))->format("d-m-Y");
}
]);
$table->create();
$table->render();

View File

@ -4,7 +4,6 @@
*/ */
use app\models\Post; use app\models\Post;
use app\models\User;
$form = new \itguild\forms\ActiveForm(); $form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/post/edit/" . $model->id : "/admin/post"); $form->beginForm(isset($model) ? "/admin/post/edit/" . $model->id : "/admin/post");
@ -18,7 +17,6 @@ $form->field(class: \itguild\forms\inputs\TextArea::class, name: "content", para
->setLabel("Пост") ->setLabel("Пост")
->render(); ->render();
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [ $form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
//$form->field(class: \itguild\forms\inputs\Select::class, name: "username", params: [
'class' => "form-control", 'class' => "form-control",
'value' => $model->user_id ?? '' 'value' => $model->user_id ?? ''
]) ])

View File

@ -7,9 +7,9 @@
use app\models\Post; use app\models\Post;
use app\models\User; use app\models\User;
use app\tables\columns\PostDeleteActionColumn; use app\tables\columns\post\PostDeleteActionColumn;
use app\tables\columns\PostEditActionColumn; use app\tables\columns\post\PostEditActionColumn;
use app\tables\columns\PostViewActionColumn; use app\tables\columns\post\PostViewActionColumn;
use Itguild\EloquentTable\EloquentDataProvider; use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable; use Itguild\EloquentTable\ListEloquentTable;
use kernel\IGTabel\btn\PrimaryBtn; use kernel\IGTabel\btn\PrimaryBtn;

View File

@ -11,20 +11,6 @@ use kernel\IGTabel\btn\DangerBtn;
use kernel\IGTabel\btn\PrimaryBtn; use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\btn\SuccessBtn; use kernel\IGTabel\btn\SuccessBtn;
//$dataProvider = new ViewJsonTableEloquentModel($content, [
// 'params' => ["class" => "table table-bordered", "border" => "2"],
// 'baseUrl' => "/admin/user",
//]);
//$table = new ViewJsonTable($dataProvider->getJson());
//$table->beforeTable(function () use ($content) {
// $btn = PrimaryBtn::create("Список", "/admin/post")->fetch();
// $btn .= SuccessBtn::create("Редактировать", "/admin/post/update/" . $content->id)->fetch();
// $btn .= DangerBtn::create("Удалить", "/admin/post/delete/" . $content->id)->fetch();
// return $btn;
//});
//$table->create();
//$table->render();
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($content, [ $table = new ViewEloquentTable(new ViewJsonTableEloquentModel($content, [
'params' => ["class" => "table table-bordered", "border" => "2"], 'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/post", 'baseUrl' => "/admin/post",

View File

@ -1 +0,0 @@
<?php

View File

@ -5,9 +5,9 @@
*/ */
use app\models\User; use app\models\User;
use app\tables\columns\UserDeleteActionColumn; use app\tables\columns\user\UserDeleteActionColumn;
use app\tables\columns\UserEditActionColumn; use app\tables\columns\user\UserEditActionColumn;
use app\tables\columns\UserViewActionColumn; use app\tables\columns\user\UserViewActionColumn;
use Itguild\EloquentTable\EloquentDataProvider; use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable; use Itguild\EloquentTable\ListEloquentTable;
use kernel\IGTabel\btn\PrimaryBtn; use kernel\IGTabel\btn\PrimaryBtn;

View File

@ -11,20 +11,6 @@ use kernel\IGTabel\btn\DangerBtn;
use kernel\IGTabel\btn\PrimaryBtn; use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\btn\SuccessBtn; use kernel\IGTabel\btn\SuccessBtn;
//$dataProvider = new ViewJsonTableEloquentModel($user, [
// 'params' => ["class" => "table table-bordered", "border" => "2"],
// 'baseUrl' => "/admin/user",
//]);
//$table = new ViewJsonTable($dataProvider->getJson());
//$table->beforeTable(function () use ($user) {
// $btn = PrimaryBtn::create("Список", "/admin/user")->fetch();
// $btn .= SuccessBtn::create("Редактировать", "/admin/user/update/" . $user->id)->fetch();
// $btn .= DangerBtn::create("Удалить", "/admin/user/delete/" . $user->id)->fetch();
// return $btn;
//});
//$table->create();
//$table->render();
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($user, [ $table = new ViewEloquentTable(new ViewJsonTableEloquentModel($user, [
'params' => ["class" => "table table-bordered", "border" => "2"], 'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/user", 'baseUrl' => "/admin/user",