kernel update. composer.lock to gitignore

This commit is contained in:
Билай Станислав 2024-12-17 13:00:13 +03:00
parent c7549c225f
commit 499f2a37d2
49 changed files with 986 additions and 3376 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ vendor
views_cache views_cache
resources/upload resources/upload
resources/tmp resources/tmp
composer.lock

View File

@ -13,7 +13,7 @@ const KERNEL_MODULES_DIR = __DIR__ . "/kernel/modules";
const KERNEL_ADMIN_THEMES_DIR = __DIR__ . "/kernel/admin_themes"; const KERNEL_ADMIN_THEMES_DIR = __DIR__ . "/kernel/admin_themes";
const CONSOLE_DIR = __DIR__ . "/kernel/console"; const CONSOLE_DIR = __DIR__ . "/kernel/console";
const RESOURCES_DIR = __DIR__ . "/resources"; const RESOURCES_DIR = __DIR__ . "/resources";
const KERNEL_TEMPLATES_DIR = __DIR__ . "/kernel/templates";
const KERNEL_APP_MODULES_DIR = KERNEL_DIR . "/app_modules"; const KERNEL_APP_MODULES_DIR = KERNEL_DIR . "/app_modules";
const APP_DIR = ROOT_DIR . "/app"; const APP_DIR = ROOT_DIR . "/app";
@ -29,6 +29,7 @@ function getConst($text): array|false|string
"{KERNEL}" => KERNEL_DIR, "{KERNEL}" => KERNEL_DIR,
"{KERNEL_MODULES}" => KERNEL_MODULES_DIR, "{KERNEL_MODULES}" => KERNEL_MODULES_DIR,
"{KERNEL_APP_MODULES}" => KERNEL_APP_MODULES_DIR, "{KERNEL_APP_MODULES}" => KERNEL_APP_MODULES_DIR,
"{KERNEL_TEMPLATES}" => KERNEL_TEMPLATES_DIR,
"{CONSOLE}" => CONSOLE_DIR, "{CONSOLE}" => CONSOLE_DIR,
"{APP}" => APP_DIR, "{APP}" => APP_DIR,
]; ];

View File

@ -2,7 +2,7 @@
$secure_config = [ $secure_config = [
'web_auth_type' => 'email_code', // login_password, email_code 'web_auth_type' => 'email_code', // login_password, email_code
'token_type' => 'crypt', // random_bytes, md5, crypt, hash, JWT 'token_type' => 'hash', // random_bytes, md5, crypt, hash, JWT
'token_expired_time' => "+30 days", // +1 day 'token_expired_time' => "+30 days", // +1 day
]; ];

View File

@ -19,7 +19,9 @@
"firebase/php-jwt": "^6.10", "firebase/php-jwt": "^6.10",
"k-adam/env-editor": "^2.0", "k-adam/env-editor": "^2.0",
"guzzlehttp/guzzle": "^7.9", "guzzlehttp/guzzle": "^7.9",
"phpmailer/phpmailer": "^6.9" "phpmailer/phpmailer": "^6.9",
"zircote/swagger-php": "^4.11",
"doctrine/annotations": "^2.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

3292
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -46,8 +46,16 @@ class CgRouteCollector extends RouteCollector
//TODO //TODO
} }
public function console($route, $handler, array $filters = []): void /**
* @param $route
* @param $handler
* @param array $filters
* @param array $additionalInfo
* @return void
*/
public function console($route, $handler, array $filters = [], array $additionalInfo = []): void
{ {
$this->addRoute(Route::GET, $route, $handler, $filters); $additionalInfo['type'] = "console";
$this->addRoute(Route::GET, $route, $handler, $filters, $additionalInfo);
} }
} }

View File

@ -10,6 +10,8 @@ class CgView
public array $varToLayout = []; public array $varToLayout = [];
public bool|string $layout = false; public bool|string $layout = false;
protected array $metaArr = [];
public function __construct() public function __construct()
{ {
@ -34,14 +36,37 @@ class CgView
$this->varToLayout[$key] = $value; $this->varToLayout[$key] = $value;
} }
private function createContent(string $view, array $data = []): false|string public function setTitle(string $title): void
{
$this->addVarToLayout('title', $title);
}
public function setMeta(array $meta): void
{
foreach ($meta as $key => $value){
$this->metaArr[$key] = $value;
}
}
public function getMeta(): string
{
$meta = "";
foreach ($this->metaArr as $key => $value){
$meta .= "<meta name='$key' content='$value'>";
}
return $meta;
}
private function createContent(string $viewFile, array $data = []): false|string
{ {
ob_start(); ob_start();
$view = $this;
foreach ($data as $key => $datum) { foreach ($data as $key => $datum) {
${"$key"} = $datum; ${"$key"} = $datum;
} }
include($this->viewPath . $view); include($this->viewPath . $viewFile);
$content = ob_get_contents(); $content = ob_get_contents();
ob_end_clean(); ob_end_clean();
@ -50,6 +75,10 @@ class CgView
$file_content = $content; $file_content = $content;
if (!isset($title)){
$title = "No Title";
}
$layoutPath = $this->viewPath; $layoutPath = $this->viewPath;
if ($this->layout) { if ($this->layout) {

View File

@ -2,15 +2,18 @@
/** /**
* @var $content * @var $content
* @var string $resources * @var string $resources
* @var string $title
* @var \kernel\CgView $view
*/ */
\Josantonius\Session\Facades\Session::start(); \Josantonius\Session\Facades\Session::start();
?> ?>
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<title>Sidebar 01</title> <title><?= $title ?></title>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<?= $view->getMeta() ?>
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet">

View File

@ -0,0 +1,10 @@
<?php
namespace kernel\app_modules\slider\controllers;
use kernel\RestController;
class SliderRestController extends RestController
{
}

View File

@ -4,6 +4,8 @@
namespace kernel\console; namespace kernel\console;
use kernel\helpers\Debug;
class Out class Out
{ {
private $foreground_colors = array(); private $foreground_colors = array();
@ -64,6 +66,11 @@ class Out
echo $this->get($string, $foreground_color, $background_color) . "\n"; echo $this->get($string, $foreground_color, $background_color) . "\n";
} }
public function inLine($string, $foreground_color = null, $background_color = null): void
{
echo $this->get($string, $foreground_color, $background_color) ;
}
// Returns all foreground color names // Returns all foreground color names
public function getForegroundColors() public function getForegroundColors()
{ {
@ -75,4 +82,16 @@ class Out
{ {
return array_keys($this->background_colors); return array_keys($this->background_colors);
} }
// public function printHeaderTable(): void
// {
// echo "\n+-----------------------------+-----------------------------+-----------------------------+-----------------------------+\n";
// printf("%-30s", "| Routs");
// printf("%-30s", "| Description");
// printf("%-30s", "| Params");
// printf("%-30s", "| Params description");
// printf("%-30s", "|");
// echo "\n+-----------------------------+-----------------------------+-----------------------------+-----------------------------+\n";
// }
} }

View File

@ -27,7 +27,7 @@ class KernelController extends ConsoleController
if (file_exists(ROOT_DIR . $this->argv['path'])) { if (file_exists(ROOT_DIR . $this->argv['path'])) {
$tmpKernelDirFull = RESOURCES_DIR . '/tmp/ad/kernel/kernel'; $tmpKernelDirFull = RESOURCES_DIR . '/tmp/ad/kernel/kernel';
$this->files->copy_folder(KERNEL_DIR, $tmpKernelDirFull); $this->files->copy_folder(ROOT_DIR . $this->argv['path'], $tmpKernelDirFull);
$this->out->r("Ядро скопировано во временную папку", 'green'); $this->out->r("Ядро скопировано во временную папку", 'green');
} else { } else {
$this->out->r("Ядро не найдено", 'red'); $this->out->r("Ядро не найдено", 'red');
@ -65,11 +65,19 @@ class KernelController extends ConsoleController
$this->out->r("/composer.json не найден", 'red'); $this->out->r("/composer.json не найден", 'red');
} }
if (!is_dir(RESOURCES_DIR . '/tmp/app')) { if (!is_dir(RESOURCES_DIR . '/tmp/kernel')) {
mkdir(RESOURCES_DIR . '/tmp/app'); mkdir(RESOURCES_DIR . '/tmp/kernel');
}
if (file_exists(KERNEL_DIR . '/manifest.json')) {
$manifest = json_decode(file_get_contents(KERNEL_DIR . '/manifest.json'), true);
$version = $manifest['version'] ?? '';
$this->files->pack(RESOURCES_DIR . '/tmp/ad/kernel/', RESOURCES_DIR . '/tmp/kernel/kernel_v' . $version . '.igk');
}
else {
$this->files->pack(RESOURCES_DIR . '/tmp/ad/kernel/', RESOURCES_DIR . '/tmp/kernel/kernel.igk');
} }
$this->files->pack(RESOURCES_DIR . '/tmp/ad/kernel/', RESOURCES_DIR . '/tmp/kernel/kernel.igk');
$this->files->recursiveRemoveDir(RESOURCES_DIR . '/tmp/ad/kernel/'); $this->files->recursiveRemoveDir(RESOURCES_DIR . '/tmp/ad/kernel/');
} }

View File

@ -2,7 +2,9 @@
namespace kernel\console\controllers; namespace kernel\console\controllers;
use kernel\App;
use kernel\console\ConsoleController; use kernel\console\ConsoleController;
use kernel\helpers\Debug;
class MainController extends ConsoleController class MainController extends ConsoleController
{ {
@ -12,4 +14,25 @@ class MainController extends ConsoleController
$this->out->r("Привет", "green"); $this->out->r("Привет", "green");
} }
public function actionHelp(): void
{
$routs = App::$collector->getData()->getStaticRoutes();
foreach ($routs as $rout => $data){
$additionalInfo = $data['GET'][3];
if (isset($additionalInfo['description']) and $additionalInfo['type'] === "console"){
$this->out->inLine($rout . " - ", "green");
$this->out->inLine($additionalInfo['description'], 'yellow');
$this->out->r("");
if (isset($additionalInfo['params'])){
foreach ($additionalInfo['params'] as $key => $param){
$this->out->inLine($key . " - ", "green");
$this->out->inLine($param, 'yellow');
$this->out->r("");
}
}
$this->out->r("");
}
}
}
} }

View File

@ -90,4 +90,33 @@ class ModuleController extends ConsoleController
} }
} }
public function actionConstructModule(): void
{
$this->out->r("Введите slug модуля:", 'yellow');
$slug = substr(fgets(STDIN), 0, -1);
$slug = strtolower($slug);
$this->out->r("Введите название модуля:", 'yellow');
$name = substr(fgets(STDIN), 0, -1);
$this->out->r("Введите автора модуля:", 'yellow');
$author = substr(fgets(STDIN), 0, -1);
$this->out->r("Введите название пунтка меню для модуля:", 'yellow');
$label = substr(fgets(STDIN), 0, -1);
$moduleService = new ModuleService();
$moduleService->createDirs($slug);
$moduleService->createModuleByParams([
'slug' => $slug,
'model' => ucfirst($slug),
'author' => $author,
'name' => $name,
'label' => $label,
]);
$this->out->r("Модуль $slug создан", 'green');
}
} }

View File

@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration return new class extends Migration
{ {
public string $migration;
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -1,41 +1,96 @@
<?php <?php
use kernel\App; use kernel\App;
use kernel\console\controllers\MigrationController;
use Phroute\Phroute\RouteCollector; use Phroute\Phroute\RouteCollector;
App::$collector->console("hello", [\kernel\console\controllers\MainController::class, "indexAction"]); App::$collector->console("hello", [\kernel\console\controllers\MainController::class, "indexAction"]);
App::$collector->console("help", [\kernel\console\controllers\MainController::class, "actionHelp"]);
App::$collector->group(["prefix" => "migration"], callback: function (RouteCollector $router){ App::$collector->group(["prefix" => "migration"], callback: function (RouteCollector $router){
App::$collector->console('run', [\kernel\console\controllers\MigrationController::class, 'actionRun']); App::$collector->console('run',
App::$collector->console('init', [\kernel\console\controllers\MigrationController::class, 'actionCreateMigrationTable']); [MigrationController::class, 'actionRun'],
App::$collector->console('create', [\kernel\console\controllers\MigrationController::class, 'actionCreate']); additionalInfo: ['description' => 'Запуск существующих миграций']
App::$collector->console('rollback', [\kernel\console\controllers\MigrationController::class, 'actionRollback']); );
App::$collector->console('init',
[MigrationController::class, 'actionCreateMigrationTable'],
additionalInfo: ['description' => 'Инициализация миграций']
);
App::$collector->console('create',
[MigrationController::class, 'actionCreate'],
additionalInfo: ['description' => 'Создание миграции', 'params' => ['--name' => 'Название миграции', '--path' => 'Путь по которому будет создана миграция']]
);
App::$collector->console('rollback',
[MigrationController::class, 'actionRollback'],
additionalInfo: ['description' => 'Откатить миграции']
);
}); });
App::$collector->group(["prefix" => "admin-theme"], callback: function (RouteCollector $router){ App::$collector->group(["prefix" => "admin-theme"], callback: function (RouteCollector $router){
App::$collector->console('install', [\kernel\console\controllers\AdminThemeController::class, 'actionInstallTheme']); App::$collector->console('install',
App::$collector->console('uninstall', [\kernel\console\controllers\AdminThemeController::class, 'actionUninstallTheme']); [\kernel\console\controllers\AdminThemeController::class, 'actionInstallTheme'],
additionalInfo: ['description' => 'Установить тему админ-панели', 'params' => ['--path' => 'Путь к устанавливаемой теме']]
);
App::$collector->console('uninstall',
[\kernel\console\controllers\AdminThemeController::class, 'actionUninstallTheme'],
additionalInfo: ['description' => 'Удалить тему админ-панели', 'params' => ['--path' => 'Путь к удаляемой теме']]
);
}); });
App::$collector->group(["prefix" => "secure"], callback: function (RouteCollector $router){ App::$collector->group(["prefix" => "secure"], callback: function (RouteCollector $router){
App::$collector->console('create-secret-key', [\kernel\console\controllers\SecureController::class, 'actionCreateSecretKey']); App::$collector->console('create-secret-key',
[\kernel\console\controllers\SecureController::class, 'actionCreateSecretKey'],
additionalInfo: ['description' => 'Генерация секрктного ключа и запись его в .env']
);
}); });
App::$collector->group(["prefix" => "admin"], callback: function (RouteCollector $router){ App::$collector->group(["prefix" => "admin"], callback: function (RouteCollector $router){
App::$collector->console('init', [\kernel\console\controllers\AdminConsoleController::class, 'actionInit']); App::$collector->console('init',
[\kernel\console\controllers\AdminConsoleController::class, 'actionInit'],
additionalInfo: ['description' => 'Инициализация админ-панели']
);
}); });
App::$collector->group(["prefix" => "module"], callback: function (RouteCollector $router){ App::$collector->group(["prefix" => "module"], callback: function (RouteCollector $router){
App::$collector->console('install', [\kernel\console\controllers\ModuleController::class, 'actionInstallModule']); App::$collector->console('install',
App::$collector->console('uninstall', [\kernel\console\controllers\ModuleController::class, 'actionUninstallModule']); [\kernel\console\controllers\ModuleController::class, 'actionInstallModule'],
App::$collector->console('pack', [\kernel\console\controllers\ModuleController::class, 'actionPackModule']); additionalInfo: ['description' => 'Установка модуля', 'params' => ['--path' => 'Путь к устанавливаемому модулю']]
App::$collector->console('update', [\kernel\console\controllers\ModuleController::class, 'actionUpdateModule']); );
App::$collector->console('uninstall',
[\kernel\console\controllers\ModuleController::class, 'actionUninstallModule'],
additionalInfo: ['description' => 'Удалить модуль', 'params' => ['--path' => 'Путь к удаляемому модулю']]
);
App::$collector->console('pack',
[\kernel\console\controllers\ModuleController::class, 'actionPackModule'],
additionalInfo: ['description' => 'Заархивировать модуль', 'params' => ['--path' => 'Путь к модулю, который нужно заархивировать']]
);
App::$collector->console('update',
[\kernel\console\controllers\ModuleController::class, 'actionUpdateModule'],
additionalInfo: ['description' => 'Обновить модуль', 'params' => ['--path' => 'Путь к архиву с модулем']]
);
App::$collector->console('construct',
[\kernel\console\controllers\ModuleController::class, 'actionConstructModule'],
additionalInfo: ['description' => 'Сгенерировать модуль']
);
}); });
App::$collector->group(["prefix" => "kernel"], callback: function (RouteCollector $router){ App::$collector->group(["prefix" => "kernel"], callback: function (RouteCollector $router){
// App::$collector->console('install', [\kernel\console\controllers\ModuleController::class, 'actionInstallModule']); App::$collector->console('pack',
// App::$collector->console('uninstall', [\kernel\console\controllers\ModuleController::class, 'actionUninstallModule']); [\kernel\console\controllers\KernelController::class, 'actionPackKernel'],
App::$collector->console('pack', [\kernel\console\controllers\KernelController::class, 'actionPackKernel']); additionalInfo: ['description' => 'Заархивировать ядро', 'params' => ['--path' => 'Путь к ядру']]
App::$collector->console('update', [\kernel\console\controllers\KernelController::class, 'actionUpdateKernel']); );
App::$collector->console('update',
[\kernel\console\controllers\KernelController::class, 'actionUpdateKernel'],
additionalInfo: [
'description' => 'Обновить модуль',
'params' =>
[
'--path' => 'Путь к архиву ядра',
'bootstrap' => 'Обновить bootstrap',
'composer' => 'Обновить composer',
'env' => 'Обновить .env.example'
]
]
);
}); });

View File

@ -12,6 +12,7 @@ use kernel\models\Option;
use kernel\modules\module_shop_client\services\ModuleShopClientService; use kernel\modules\module_shop_client\services\ModuleShopClientService;
use kernel\modules\user\service\UserService; use kernel\modules\user\service\UserService;
use kernel\Request; use kernel\Request;
use kernel\services\MigrationService;
use kernel\services\ModuleService; use kernel\services\ModuleService;
class ModuleController extends AdminController class ModuleController extends AdminController

8
kernel/manifest.json Normal file
View File

@ -0,0 +1,8 @@
{
"name": "Kernel",
"version": "0.2",
"author": "ITGuild",
"slug": "kernel",
"type": "kernel",
"description": "Kernel"
}

View File

@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration return new class extends Migration
{ {
public string $migration;
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -12,8 +12,8 @@ use kernel\helpers\Files;
use kernel\helpers\RESTClient; use kernel\helpers\RESTClient;
use kernel\helpers\SMTP; use kernel\helpers\SMTP;
use kernel\Mailing; use kernel\Mailing;
use kernel\modules\module_shop_client\services\ModuleShopClientService;
use kernel\Request; use kernel\Request;
use kernel\services\KernelService;
use kernel\services\ModuleService; use kernel\services\ModuleService;
use kernel\services\ModuleShopService; use kernel\services\ModuleShopService;
use kernel\services\TokenService; use kernel\services\TokenService;
@ -24,6 +24,7 @@ class ModuleShopClientController extends AdminController
protected Client $client; protected Client $client;
protected ModuleService $moduleService; protected ModuleService $moduleService;
protected KernelService $kernelService;
protected function init(): void protected function init(): void
{ {
@ -32,6 +33,7 @@ class ModuleShopClientController extends AdminController
$this->client = new Client(); $this->client = new Client();
$this->moduleService = new ModuleService(); $this->moduleService = new ModuleService();
$this->kernelService = new KernelService();
} }
/** /**
@ -55,6 +57,7 @@ class ModuleShopClientController extends AdminController
'page_number' => $page_number, 'page_number' => $page_number,
'module_count' => $module_count, 'module_count' => $module_count,
'per_page' => $per_page, 'per_page' => $per_page,
'kernelService' => new KernelService(),
]); ]);
} else { } else {
$this->cgView->render("module_shop_error_connection.php"); $this->cgView->render("module_shop_error_connection.php");
@ -112,6 +115,36 @@ class ModuleShopClientController extends AdminController
$this->redirect('/admin/module_shop_client', 302); $this->redirect('/admin/module_shop_client', 302);
} }
public function actionRenderKernelUpdateForm(): void
{
$this->cgView->render("kernel_update.php");
}
#[NoReturn] public function actionKernelUpdate(): void
{
$request = new Request();
$modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug');
$modules_info = json_decode($modules_info->getBody()->getContents(), true);
foreach ($modules_info as $module) {
if ($module['slug'] === 'kernel') {
$path = $module['path_to_archive'];
}
}
if (isset($path)) {
Files::uploadByUrl($_ENV['MODULE_SHOP_URL'] . $path, RESOURCES_DIR . "/tmp/kernel");
if ($this->kernelService->updateKernel('/resources/tmp/kernel/' . basename($path))) {
Flash::setMessage("success", "Ядро успешно обновлено.");
} else {
Flash::setMessage("error", "Ошибка обновления ядра.");
}
} else {
Flash::setMessage("error", "Ошибка обновления ядра.");
}
$this->redirect('/admin/module_shop_client', 302);
}
#[NoReturn] public function actionDelete(): void #[NoReturn] public function actionDelete(): void
{ {
$request = new Request(); $request = new Request();
@ -131,13 +164,6 @@ class ModuleShopClientController extends AdminController
$request = new Request(); $request = new Request();
$address = $request->post("email"); $address = $request->post("email");
// $mailing = new Mailing();
// $mailing->send_html("login_by_code.php", ['code' => mt_rand(100000, 999999)], [
// 'address' => $address,
// 'subject' => "Код авторизации",
// "from_name" => $_ENV['APP_NAME']
// ]);
$moduleShopService = new ModuleShopService(); $moduleShopService = new ModuleShopService();
$result = $moduleShopService->email_auth($address); $result = $moduleShopService->email_auth($address);
@ -153,13 +179,6 @@ class ModuleShopClientController extends AdminController
$request = new Request(); $request = new Request();
$code = $request->post("code"); $code = $request->post("code");
// $mailing = new Mailing();
// $mailing->send_html("login_by_code.php", ['code' => mt_rand(100000, 999999)], [
// 'address' => $address,
// 'subject' => "Код авторизации",
// "from_name" => $_ENV['APP_NAME']
// ]);
$moduleShopService = new ModuleShopService(); $moduleShopService = new ModuleShopService();
$result = $moduleShopService->code_check($code); $result = $moduleShopService->code_check($code);

View File

@ -17,6 +17,10 @@ App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){
App::$collector->get('/update', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionUpdate']); App::$collector->get('/update', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionUpdate']);
App::$collector->post('/auth', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionAuth']); App::$collector->post('/auth', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionAuth']);
App::$collector->post('/code_check', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionCodeCheck']); App::$collector->post('/code_check', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionCodeCheck']);
App::$collector->group(["prefix" => "kernel"], function (RouteCollector $router) {
App::$collector->get('/update_form', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionRenderKernelUpdateForm']);
App::$collector->post('/update', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionKernelUpdate']);
});
}); });
}); });
}); });

View File

@ -5,6 +5,7 @@
* @var int $page_number * @var int $page_number
* @var int $per_page * @var int $per_page
* @var \kernel\services\ModuleService $moduleService * @var \kernel\services\ModuleService $moduleService
* @var \kernel\services\KernelService $kernelService
*/ */
use Itguild\Tables\ListJsonTable; use Itguild\Tables\ListJsonTable;
@ -37,21 +38,23 @@ $table->addAction(function ($row, $url) use ($moduleService) {
}); });
$table->addAction(function ($row, $url) use ($moduleService){ $table->addAction(function ($row, $url) use ($moduleService){
if ($moduleService->isInstall($row['slug'])){ if ($row['slug'] !== 'kernel') {
$url = "$url/delete/?slug=" . $row['slug']; if ($moduleService->isInstall($row['slug'])) {
$url = "$url/delete/?slug=" . $row['slug'];
return \kernel\widgets\IconBtn\IconBtnDeleteWidget::create(['url' => $url])->run(); return \kernel\widgets\IconBtn\IconBtnDeleteWidget::create(['url' => $url])->run();
} } else {
else { $url = "$url/install/?id=" . $row['id'];
$url = "$url/install/?id=" . $row['id'];
return \kernel\widgets\IconBtn\IconBtnInstallWidget::create(['url' => $url])->run(); return \kernel\widgets\IconBtn\IconBtnInstallWidget::create(['url' => $url])->run();
}
} }
return null;
}); });
$table->addAction(function ($row, $url) use ($moduleService){ $table->addAction(function ($row, $url) use ($moduleService, $kernelService){
$slug = $row['slug']; $slug = $row['slug'];
if ($moduleService->isInstall($slug)){ if ($moduleService->isInstall($slug)) {
if (!$moduleService->isLastVersion($slug)) { if (!$moduleService->isLastVersion($slug)) {
$url = "$url/update/?slug=" . $slug; $url = "$url/update/?slug=" . $slug;
@ -59,6 +62,14 @@ $table->addAction(function ($row, $url) use ($moduleService){
} }
} }
if ($slug === 'kernel') {
if (!$kernelService->isLastVersion()) {
$url = "$url/kernel/update_form/";
return \kernel\widgets\IconBtn\IconBtnUpdateWidget::create(['url' => $url])->run();
}
}
return false; return false;
}); });

View File

@ -0,0 +1,39 @@
<?php
use itguild\forms\ActiveForm;
\kernel\widgets\ModuleTabsWidget::create()->run();
echo \kernel\helpers\Html::h(2, "Выберите нужные файлы для обновления");
$form = new ActiveForm();
$form->beginForm("/admin/module_shop_client/kernel/update/", enctype: 'multipart/form-data');
$form->field(\itguild\forms\inputs\Select::class, "files[]", [
'class' => "form-control",
'multiple' => "multiple",
])
->setLabel("Дополнительные файлы")
->setOptions([
'.env.example' => '.env.example',
'bootstrap.php' => 'bootstrap',
'composer.json' => 'composer.json',
])
->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>
<?php
$form->endForm();

View File

@ -9,7 +9,7 @@ echo \kernel\helpers\Html::h(2, "Форма авторизации/регист
$form = new ActiveForm(); $form = new ActiveForm();
$form->beginForm("/admin/module_shop_client/auth/"); $form->beginForm("/admin/module_shop_client/auth/");
$form->field(\itguild\forms\inputs\TextInput::class, 'email', [ $form->field(\itguild\forms\inputs\EmailInput::class, 'email', [
'class' => "form-control", 'class' => "form-control",
'placeholder' => 'Email', 'placeholder' => 'Email',
]) ])

View File

@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration return new class extends Migration
{ {
public string $migration;
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -5,17 +5,22 @@ namespace kernel\modules\post;
use kernel\helpers\Debug; use kernel\helpers\Debug;
use kernel\Module; use kernel\Module;
use kernel\modules\menu\service\MenuService; use kernel\modules\menu\service\MenuService;
use kernel\services\MigrationService;
class PostModule extends Module class PostModule extends Module
{ {
public MenuService $menuService; public MenuService $menuService;
public MigrationService $migrationService;
public function __construct() public function __construct()
{ {
$this->menuService = new MenuService(); $this->menuService = new MenuService();
$this->migrationService = new MigrationService();
} }
public function init(): void public function init(): void
{ {
$this->migrationService->runAtPath("{KERNEL_MODULES}/post/migrations");
$this->menuService->createItem([ $this->menuService->createItem([
"label" => "Посты", "label" => "Посты",
"url" => "/admin/post", "url" => "/admin/post",
@ -26,5 +31,6 @@ class PostModule extends Module
public function deactivate(): void public function deactivate(): void
{ {
$this->menuService->removeItemBySlug("post"); $this->menuService->removeItemBySlug("post");
$this->migrationService->rollbackAtPath("{KERNEL_MODULES}/post/migrations");
} }
} }

View File

@ -6,6 +6,8 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration return new class extends Migration
{ {
public string $migration;
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -3,16 +3,13 @@
/** /**
* @var \Illuminate\Database\Eloquent\Collection $contents * @var \Illuminate\Database\Eloquent\Collection $contents
* @var int $page_number * @var int $page_number
* @var \kernel\CgView $view
*/ */
use kernel\IGTabel\action_column\DeleteActionColumn;
use kernel\IGTabel\action_column\EditActionColumn;
use kernel\IGTabel\action_column\ViewActionColumn;
use kernel\modules\post\models\Post; use kernel\modules\post\models\Post;
use kernel\modules\user\models\User; use kernel\modules\user\models\User;
use Itguild\EloquentTable\EloquentDataProvider; use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable; use Itguild\EloquentTable\ListEloquentTable;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\widgets\IconBtn\IconBtnCreateWidget; use kernel\widgets\IconBtn\IconBtnCreateWidget;
use kernel\widgets\IconBtn\IconBtnDeleteWidget; use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget; use kernel\widgets\IconBtn\IconBtnEditWidget;
@ -25,6 +22,11 @@ $table = new ListEloquentTable(new EloquentDataProvider(Post::class, [
'baseUrl' => "/admin/post" 'baseUrl' => "/admin/post"
])); ]));
$view->setTitle("Список постов");
$view->setMeta([
'description' => 'Список постов системы'
]);
$entityRelation = new \kernel\EntityRelation(); $entityRelation = new \kernel\EntityRelation();
$additionals = $entityRelation->getEntityRelationsBySlug("post"); $additionals = $entityRelation->getEntityRelationsBySlug("post");

View File

@ -7,9 +7,6 @@
use kernel\modules\user\models\User; use kernel\modules\user\models\User;
use Itguild\EloquentTable\ViewEloquentTable; use Itguild\EloquentTable\ViewEloquentTable;
use Itguild\EloquentTable\ViewJsonTableEloquentModel; use Itguild\EloquentTable\ViewJsonTableEloquentModel;
use kernel\IGTabel\btn\DangerBtn;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\btn\SuccessBtn;
use kernel\widgets\IconBtn\IconBtnDeleteWidget; use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget; use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnListWidget; use kernel\widgets\IconBtn\IconBtnListWidget;

View File

@ -36,14 +36,16 @@ class SecureRestController extends RestController
$res = []; $res = [];
if ($model) { if ($model) {
if (password_verify($data["password"], $model->password_hash)) { if (password_verify($data["password"], $model->password_hash)) {
$model->access_token_expires_at = date("Y-m-d H:i:s", strtotime(App::$secure['token_expired_time'])); if ($model->access_token_expires_at < date("Y-m-d H:i:s") or $model->access_token === null){
$model->access_token = match (App::$secure['token_type']) { $model->access_token_expires_at = date("Y-m-d H:i:s", strtotime(App::$secure['token_expired_time']));
"JWT" => TokenService::JWT($_ENV['SECRET_KEY'], 'HS256'), $model->access_token = match (App::$secure['token_type']) {
"md5" => TokenService::md5(), "JWT" => TokenService::JWT($_ENV['SECRET_KEY'], 'HS256'),
"crypt" => TokenService::crypt(), "md5" => TokenService::md5(),
"hash" => TokenService::hash('sha256'), "crypt" => TokenService::crypt(),
default => TokenService::random_bytes(20), "hash" => TokenService::hash('sha256'),
}; default => TokenService::random_bytes(20),
};
}
$res = [ $res = [
"access_token" => $model->access_token, "access_token" => $model->access_token,

View File

@ -6,6 +6,8 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration return new class extends Migration
{ {
public string $migration;
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -6,6 +6,8 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration return new class extends Migration
{ {
public string $migration;
/** /**
* Run the migrations. * Run the migrations.
* *

View File

@ -0,0 +1,21 @@
<?php
namespace kernel\services;
class ConsoleService
{
public function runComposerRequire(string $package): void
{
exec("composer require $package");
}
public function runComposerRemove(string $package): void
{
exec("composer remove $package");
}
public function runCommand(string $command): void
{
exec($command);
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace kernel\services;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use kernel\helpers\Manifest;
use kernel\helpers\RESTClient;
use kernel\Request;
use ZipArchive;
class KernelService
{
protected null|bool $serverAvailable = null;
protected ModuleService $moduleService;
protected Files $files;
public function __construct()
{
$this->moduleService = new ModuleService();
$this->files = new Files();
}
public function getKernelInfo(): false|array|string
{
$info = [];
$info['path'] = KERNEL_DIR;
if (file_exists(KERNEL_DIR . "/manifest.json")) {
$manifest = json_decode(file_get_contents(KERNEL_DIR . "/manifest.json"), true);
$manifest = getConst($manifest);
$info = array_merge($info, $manifest);
}
return $info;
}
public function isLastVersion(): bool
{
if ($this->moduleService->isServerAvailable()) {
$modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug');
$modules_info = json_decode($modules_info->getBody()->getContents(), true);
$kernel_info = $this->getKernelInfo();
foreach ($modules_info as $mod) {
if ($mod['slug'] === $kernel_info['slug'] && $mod['version'] === $kernel_info['version']) {
return true;
}
}
}
return false;
}
public function updateKernel(string $path): bool
{
$request = new Request();
$files = $request->post('files');
$zip = new ZipArchive;
if (file_exists(ROOT_DIR . $path)) {
$tmpKernelDir = md5(time());
$res = $zip->open(ROOT_DIR . $path);
if ($res === TRUE) {
$tmpKernelDirFull = RESOURCES_DIR . '/tmp/kernel/' . $tmpKernelDir . "/";
$zip->extractTo($tmpKernelDirFull);
$zip->close();
$this->files->recursiveRemoveKernelDir();
$this->files->copy_folder($tmpKernelDirFull . 'kernel' , ROOT_DIR . "/kernel");
foreach ($files as $file) {
if ($file === 'bootstrap') {
$this->files->recursiveRemoveDir(ROOT_DIR . '/bootstrap');
$this->files->copy_folder($tmpKernelDirFull . 'bootstrap' , ROOT_DIR . '/bootstrap');
}
copy($tmpKernelDirFull . $file , ROOT_DIR . '/' . $file);
}
$this->files->recursiveRemoveDir($tmpKernelDirFull);
unlink(ROOT_DIR . $path);
return true;
}
}
return false;
}
}

View File

@ -36,4 +36,25 @@ class MigrationService
} }
} }
public function rollbackAtPath(string $path): void
{
$path = getConst($path);
try {
$filesystem = new Filesystem();
$dmr = new DatabaseMigrationRepository(App::$db->capsule->getDatabaseManager(), 'migration');
$m = new Migrator($dmr, App::$db->capsule->getDatabaseManager(), $filesystem);
$migrationFiles = $m->getMigrationFiles($path);
foreach ($migrationFiles as $name => $migrationFile){
$migrationInstance = $filesystem->getRequire($migrationFile);
$migrationInstance->migration = $name;
$migrationInstance->down();
$dmr->delete($migrationInstance);
}
} catch (\Exception $e) {
throw new \Exception('Не удалось откатить миграции');
}
}
} }

View File

@ -10,7 +10,6 @@ use kernel\helpers\Files;
use kernel\helpers\Manifest; use kernel\helpers\Manifest;
use kernel\helpers\RESTClient; use kernel\helpers\RESTClient;
use kernel\models\Option; use kernel\models\Option;
use MongoDB\Driver\Session;
use ZipArchive; use ZipArchive;
class ModuleService class ModuleService
@ -444,10 +443,11 @@ class ModuleService
public function isLastVersion(string $slug): bool public function isLastVersion(string $slug): bool
{ {
if ($this->isServerAvailable()){ if ($this->isServerAvailable()) {
$modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug'); $modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug');
$modules_info = json_decode($modules_info->getBody()->getContents(), true); $modules_info = json_decode($modules_info->getBody()->getContents(), true);
$mod_info = $this->getModuleInfoBySlug($slug); $mod_info = $this->getModuleInfoBySlug($slug);
foreach ($modules_info as $mod) { foreach ($modules_info as $mod) {
if ($mod['slug'] === $mod_info['slug'] && $mod['version'] === $mod_info['version']) { if ($mod['slug'] === $mod_info['slug'] && $mod['version'] === $mod_info['version']) {
@ -473,18 +473,20 @@ class ModuleService
public function isShopModule(string $slug): bool public function isShopModule(string $slug): bool
{ {
if ($this->isServerAvailable()){ if ($this->isServerAvailable()) {
$modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug'); $modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug');
if (!$this->issetModuleShopToken()){ if (!$this->issetModuleShopToken()) {
return false; return false;
} }
$modules_info = json_decode($modules_info->getBody()->getContents(), true); $modules_info = json_decode($modules_info->getBody()->getContents(), true);
$mod_info = $this->getModuleInfoBySlug($slug); if (isset($modules_info)) {
foreach ($modules_info as $mod) { $mod_info = $this->getModuleInfoBySlug($slug);
if ($mod['slug'] === $mod_info['slug']) { foreach ($modules_info as $mod) {
return true; if ($mod['slug'] === $mod_info['slug']) {
return true;
}
} }
} }
} }
@ -505,7 +507,7 @@ class ModuleService
public function isServerAvailable(): bool public function isServerAvailable(): bool
{ {
if (null !== $this->serverAvailable){ if (null !== $this->serverAvailable) {
return $this->serverAvailable; return $this->serverAvailable;
} }
@ -522,11 +524,58 @@ class ModuleService
public function issetModuleShopToken(): bool public function issetModuleShopToken(): bool
{ {
if (!empty($_ENV['MODULE_SHOP_TOKEN'])){ if (!empty($_ENV['MODULE_SHOP_TOKEN'])) {
return true; return true;
} }
return false; return false;
} }
public function createDirs(string $slug): void
{
mkdir(KERNEL_APP_MODULES_DIR . "/$slug");
mkdir(KERNEL_APP_MODULES_DIR . "/$slug/controllers");
mkdir(KERNEL_APP_MODULES_DIR . "/$slug/migrations");
mkdir(KERNEL_APP_MODULES_DIR . "/$slug/services");
mkdir(KERNEL_APP_MODULES_DIR . "/$slug/models");
mkdir(KERNEL_APP_MODULES_DIR . "/$slug/models/forms");
mkdir(KERNEL_APP_MODULES_DIR . "/$slug/routs");
mkdir(KERNEL_APP_MODULES_DIR . "/$slug/views");
mkdir(APP_DIR . "/modules/$slug");
mkdir(APP_DIR . "/modules/$slug/controllers");
mkdir(APP_DIR . "/modules/$slug/routs");
}
public function createModuleByParams(array $params): void
{
$slug = $params['slug'];
$model = $params['model'];
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/manifests/manifest_template', APP_DIR . "/modules/$slug/manifest.json", $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/controllers/kernel_controller_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/controllers/' . $model . 'Controller.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/controllers/app_controller_template', APP_DIR . '/modules/' . $slug . '/controllers/' . $model . 'Controller.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/routs/kernel_routs_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/routs/' . $slug . '.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/routs/app_routs_template', APP_DIR . '/modules/' . $slug . '/routs/' . $slug . '.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/module_files/kernel_module_file_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/' . $model . 'Module.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/module_files/app_module_file_template', APP_DIR . '/modules/' . $slug . '/' . $model . 'Module.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/models/model_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/models/' . $model . '.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/models/forms/create_form_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/models/forms/Create' . $model . 'Form.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/services/service_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/services/' . $model . 'Service.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/views/index_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/views/index.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/views/view_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/views/view.php', $params);
$this->createModuleFileByTemplate(KERNEL_TEMPLATES_DIR . '/views/form_template', KERNEL_APP_MODULES_DIR . '/' . $slug . '/views/form.php', $params);
}
public function createModuleFileByTemplate(string $templatePath, string $filePath, array $params): void
{
$data = file_get_contents($templatePath);
foreach ($params as $key => $param){
$data = str_replace("{" . $key . "}", $param, $data);
}
file_put_contents($filePath, $data);
}
} }

View File

@ -32,7 +32,7 @@ class TokenService
*/ */
public static function md5(): string public static function md5(): string
{ {
return md5(microtime() . self::getSalt() . time()); return md5(microtime() . self::getSalt(10) . time());
} }
/** /**
@ -40,7 +40,7 @@ class TokenService
*/ */
public static function crypt(): string public static function crypt(): string
{ {
return crypt(microtime(), self::getSalt()); return crypt(microtime(), self::getSalt(20));
} }
/** /**
@ -48,15 +48,15 @@ class TokenService
*/ */
public static function hash(string $alg): string public static function hash(string $alg): string
{ {
return hash($alg, self::getSalt()); return hash($alg, self::getSalt(10));
} }
/** /**
* @throws RandomException * @throws RandomException
*/ */
public static function getSalt(): string public static function getSalt(int $length): string
{ {
return bin2hex(random_bytes(10)); return bin2hex(random_bytes($length));
} }
} }

View File

@ -0,0 +1,8 @@
<?php
namespace app\modules\{slug}\controllers;
class {model}Controller extends \kernel\app_modules\{slug}\controllers\{model}Controller
{
}

View File

@ -0,0 +1,98 @@
<?php
namespace kernel\app_modules\{slug}\controllers;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\app_modules\{slug}\models\forms\Create{model}Form;
use kernel\app_modules\{slug}\models\{model};
use kernel\app_modules\{slug}\services\{model}Service;
class {model}Controller extends AdminController
{
private {model}Service ${slug}Service;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/{slug}/views/";
$this->{slug}Service = new {model}Service();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
#[NoReturn] public function actionAdd(): void
{
${slug}Form = new Create{model}Form();
${slug}Form->load($_REQUEST);
if (${slug}Form->validate()){
${slug} = $this->{slug}Service->create(${slug}Form);
if (${slug}){
$this->redirect("/admin/{slug}/view/" . ${slug}->id);
}
}
$this->redirect("/admin/{slug}/create");
}
public function actionIndex($page_number = 1): void
{
$this->cgView->render("index.php", ['page_number' => $page_number]);
}
/**
* @throws Exception
*/
public function actionView($id): void
{
${slug} = {model}::find($id);
if (!${slug}){
throw new Exception(message: "The {slug} not found");
}
$this->cgView->render("view.php", ['{slug}' => ${slug}]);
}
/**
* @throws Exception
*/
public function actionUpdate($id): void
{
$model = {model}::find($id);
if (!$model){
throw new Exception(message: "The {slug} not found");
}
$this->cgView->render("form.php", ['model' => $model]);
}
/**
* @throws Exception
*/
public function actionEdit($id): void
{
${slug} = {model}::find($id);
if (!${slug}){
throw new Exception(message: "The {slug} not found");
}
${slug}Form = new Create{model}Form();
${slug}Service = new {model}Service();
${slug}Form->load($_REQUEST);
if (${slug}Form->validate()) {
${slug} = ${slug}Service->update(${slug}Form, ${slug});
if (${slug}) {
$this->redirect("/admin/{slug}/view/" . ${slug}->id);
}
}
$this->redirect("/admin/{slug}/update/" . $id);
}
#[NoReturn] public function actionDelete($id): void
{
${slug} = {model}::find($id)->first();
${slug}->delete();
$this->redirect("/admin/{slug}/");
}
}

View File

@ -0,0 +1,11 @@
{
"name": "{name}",
"version": "0.1",
"author": "{author}",
"slug": "{slug}",
"description": "{name} module",
"module_class": "app\\modules\\{slug}\\{model}Module",
"module_class_file": "{APP}/modules/{slug}/{model}Module.php",
"routs": "routs/{slug}.php",
"migration_path": "migrations"
}

View File

@ -0,0 +1,25 @@
<?php
namespace kernel\app_modules\{slug}\models\forms;
use kernel\FormModel;
class Create{model}Form extends FormModel
{
public function rules(): array
{
// Заполнить массив правил
// Пример:
// return [
// 'label' => 'required|min-str-len:5|max-str-len:30',
// 'entity' => 'required',
// 'slug' => '',
// 'status' => ''
// ];
return [
];
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace kernel\app_modules\{slug}\models;
use Illuminate\Database\Eloquent\Model;
// Добавить @property
/**
* @property int $id
* @property int $status
*/
class {model} extends Model
{
const DISABLE_STATUS = 0;
const ACTIVE_STATUS = 1;
protected $table = '{slug}';
protected $fillable = []; // Заполнить массив. Пример: ['label', 'slug', 'status']
public static function labels(): array
{
// Заполнить массив
// Пример: [
// 'label' => 'Заголовок',
// 'entity' => 'Сущность',
// 'slug' => 'Slug',
// 'status' => 'Статус',
// ]
return [
];
}
/**
* @return string[]
*/
public static function getStatus(): array
{
return [
self::DISABLE_STATUS => "Не активный",
self::ACTIVE_STATUS => "Активный",
];
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace app\modules\{slug};
class {model}Module extends \kernel\app_modules\{slug}\{model}Module
{
}

View File

@ -0,0 +1,31 @@
<?php
namespace kernel\app_modules\{slug};
use kernel\helpers\Debug;
use kernel\Module;
use kernel\modules\menu\service\MenuService;
class {model}Module extends Module
{
public MenuService $menuService;
public function __construct()
{
$this->menuService = new MenuService();
}
public function init(): void
{
$this->menuService->createItem([
"label" => "{label}",
"url" => "/admin/{slug}",
"slug" => "{slug}",
]);
}
public function deactivate(): void
{
$this->menuService->removeItemBySlug("{slug}");
}
}

View File

@ -0,0 +1,2 @@
<?php
include KERNEL_APP_MODULES_DIR . "/{slug}/routs/{slug}.php";

View File

@ -0,0 +1,20 @@
<?php
use kernel\App;
use kernel\CgRouteCollector;
use Phroute\Phroute\RouteCollector;
App::$collector->group(["prefix" => "admin"], function (CgRouteCollector $router) {
App::$collector->group(["before" => "auth"], function (RouteCollector $router) {
App::$collector->group(["prefix" => "{slug}"], function (CGRouteCollector $router) {
App::$collector->get('/', [\app\modules\{slug}\controllers\{model}Controller::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\app\modules\{slug}\controllers\{model}Controller::class, 'actionIndex']);
App::$collector->get('/create', [\app\modules\{slug}\controllers\{model}Controller::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\{slug}\controllers\{model}Controller::class, 'actionAdd']);
App::$collector->get('/view/{id}', [\app\modules\{slug}\controllers\{model}Controller::class, 'actionView']);
App::$collector->any('/update/{id}', [\app\modules\{slug}\controllers\{model}Controller::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\app\modules\{slug}\controllers\{model}Controller::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\app\modules\{slug}\controllers\{model}Controller::class, 'actionDelete']);
});
});
});

View File

@ -0,0 +1,39 @@
<?php
namespace kernel\app_modules\{slug}\services;
use kernel\helpers\Debug;
use kernel\app_modules\{slug}\models\{model};
use kernel\FormModel;
class {model}Service
{
public function create(FormModel $form_model): false|{model}
{
$model = new {model}();
// Пример заполнения:
// $model->content = $form_model->getItem('content');
// $model->user_id = $form_model->getItem('user_id');
// $model->title = $form_model->getItem('title');
// $model->slug = Slug::createSlug($form_model->getItem('title'), {model}::class); // Генерация уникального slug
if ($model->save()){
return $model;
}
return false;
}
public function update(FormModel $form_model, {model} ${slug}): false|{model}
{
// Пример обновления:
// ${slug}->content = $form_model->getItem('content');
// ${slug}->user_id = $form_model->getItem('user_id');
if (${slug}->save()){
return ${slug};
}
return false;
}
}

View File

@ -0,0 +1,55 @@
<?php
/**
* @var {model} $model
*/
use kernel\app_modules\{slug}\models\{model};
$form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/{slug}/edit/" . $model->id : "/admin/{slug}", 'multipart/form-data');
// Пример формы:
/*
$form->field(\itguild\forms\inputs\TextInput::class, 'title', [
'class' => "form-control",
'placeholder' => 'Заголовок поста',
'value' => $model->title ?? ''
])
->setLabel("Заголовок")
->render();
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
'class' => "form-control",
'value' => $model->user_id ?? ''
])
->setLabel("Пользователи")
->setOptions(\kernel\modules\user\service\UserService::createUsernameArr())
->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,68 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection ${slug}
* @var int $page_number
* @var \kernel\CgView $view
*/
use kernel\app_modules\{slug}\models\{model};
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\widgets\IconBtn\IconBtnCreateWidget;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnViewWidget;
$view->setTitle("Список {slug}");
$view->setMeta([
'description' => 'Список {slug} системы'
]);
//Для использования таблицы с моделью, необходимо создать таблицу в базе данных
//$table = new ListEloquentTable(new EloquentDataProvider({model}::class, [
// 'currentPage' => $page_number,
// 'perPage' => 8,
// 'params' => ["class" => "table table-bordered", "border" => "2"],
// 'baseUrl' => "/admin/{slug}"
//]));
$table = new \Itguild\Tables\ListJsonTable(json_encode(
[
'meta' => [
'total' => 0,
'totalWithFilters' => 0,
'columns' => [
'title',
'slug',
'status',
],
'perPage' => 5,
'currentPage' => 1,
'baseUrl' => '/admin/some',
'params' => [
'class' => 'table table-bordered',
'border' => 2
]
],
'filters' => [],
'data' => [],
]
));
$table->beforePrint(function () {
return IconBtnCreateWidget::create(['url' => '/admin/{slug}/create'])->run();
});
$table->addAction(function($row) {
return IconBtnViewWidget::create(['url' => '/admin/{slug}/view/' . $row['id']])->run();
});
$table->addAction(function($row) {
return IconBtnEditWidget::create(['url' => '/admin/{slug}/update/' . $row['id']])->run();
});
$table->addAction(function($row) {
return IconBtnDeleteWidget::create(['url' => '/admin/{slug}/delete/' . $row['id']])->run();
});
$table->create();
$table->render();

View File

@ -0,0 +1,25 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection ${slug}
*/
use Itguild\EloquentTable\ViewEloquentTable;
use Itguild\EloquentTable\ViewJsonTableEloquentModel;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnListWidget;
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel(${slug}, [
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/{slug}",
]));
$table->beforePrint(function () use (${slug}) {
$btn = IconBtnListWidget::create(['url' => '/admin/{slug}'])->run();
$btn .= IconBtnEditWidget::create(['url' => '/admin/{slug}/update/' . ${slug}->id])->run();
$btn .= IconBtnDeleteWidget::create(['url' => '/admin/{slug}/delete/' . ${slug}->id])->run();
return $btn;
});
$table->create();
$table->render();