This commit is contained in:
kali 2024-05-02 17:52:03 +03:00
parent f26754ca79
commit 143fa9f324
25 changed files with 1083 additions and 38 deletions

View File

@ -0,0 +1,96 @@
<?php
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Source;
use Twig\Template;
/* main/index.html.twig */
class __TwigTemplate_09ccf709a9c7f01a6f9c635608c9f350 extends Template
{
private $source;
private $macros = [];
public function __construct(Environment $env)
{
parent::__construct($env);
$this->source = $this->getSourceContext();
$this->blocks = [
'title' => [$this, 'block_title'],
'content' => [$this, 'block_content'],
];
}
protected function doGetParent(array $context)
{
// line 1
return "layouts/simple.html.twig";
}
protected function doDisplay(array $context, array $blocks = [])
{
$macros = $this->macros;
$this->parent = $this->loadTemplate("layouts/simple.html.twig", "main/index.html.twig", 1);
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = [])
{
$macros = $this->macros;
echo twig_escape_filter($this->env, ($context["title"] ?? null), "html", null, true);
}
// line 5
public function block_content($context, array $blocks = [])
{
$macros = $this->macros;
// line 6
echo " ";
echo twig_escape_filter($this->env, $this->env->getFunction('create_form')->getCallable()(), "html", null, true);
echo "
";
// line 7
echo twig_escape_filter($this->env, ($context["content"] ?? null), "html", null, true);
echo "
";
}
/**
* @codeCoverageIgnore
*/
public function getTemplateName()
{
return "main/index.html.twig";
}
/**
* @codeCoverageIgnore
*/
public function isTraitable()
{
return false;
}
/**
* @codeCoverageIgnore
*/
public function getDebugInfo()
{
return array ( 63 => 7, 58 => 6, 54 => 5, 47 => 3, 36 => 1,);
}
public function getSourceContext()
{
return new Source("", "main/index.html.twig", "/home/kali/php/untitled/views/main/index.html.twig");
}
}

View File

@ -0,0 +1,98 @@
<?php
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Source;
use Twig\Template;
/* form/resultItem.html.twig */
class __TwigTemplate_94bc2d1f79a7d79af045673fc12da74a extends Template
{
private $source;
private $macros = [];
public function __construct(Environment $env)
{
parent::__construct($env);
$this->source = $this->getSourceContext();
$this->blocks = [
'title' => [$this, 'block_title'],
'content' => [$this, 'block_content'],
];
}
protected function doGetParent(array $context)
{
// line 1
return "layouts/simple.html.twig";
}
protected function doDisplay(array $context, array $blocks = [])
{
$macros = $this->macros;
$this->parent = $this->loadTemplate("layouts/simple.html.twig", "form/resultItem.html.twig", 1);
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = [])
{
$macros = $this->macros;
echo twig_escape_filter($this->env, ($context["title"] ?? null), "html", null, true);
}
// line 5
public function block_content($context, array $blocks = [])
{
$macros = $this->macros;
// line 6
echo " <h1 class=\"display-4\">";
echo twig_escape_filter($this->env, ($context["title"] ?? null), "html", null, true);
echo "</h1>
";
// line 8
echo twig_escape_filter($this->env, $this->env->getFunction('create_get_action')->getCallable()(), "html", null, true);
echo "
";
}
/**
* @codeCoverageIgnore
*/
public function getTemplateName()
{
return "form/resultItem.html.twig";
}
/**
* @codeCoverageIgnore
*/
public function isTraitable()
{
return false;
}
/**
* @codeCoverageIgnore
*/
public function getDebugInfo()
{
return array ( 64 => 8, 58 => 6, 54 => 5, 47 => 3, 36 => 1,);
}
public function getSourceContext()
{
return new Source("", "form/resultItem.html.twig", "/home/kali/php/untitled/views/form/resultItem.html.twig");
}
}

View File

@ -0,0 +1,97 @@
<?php
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Source;
use Twig\Template;
/* form/form.html.twig */
class __TwigTemplate_1782f108c6541d589defb1221fcbfccb extends Template
{
private $source;
private $macros = [];
public function __construct(Environment $env)
{
parent::__construct($env);
$this->source = $this->getSourceContext();
$this->blocks = [
'title' => [$this, 'block_title'],
'content' => [$this, 'block_content'],
];
}
protected function doGetParent(array $context)
{
// line 1
return "layouts/simple.html.twig";
}
protected function doDisplay(array $context, array $blocks = [])
{
$macros = $this->macros;
$this->parent = $this->loadTemplate("layouts/simple.html.twig", "form/form.html.twig", 1);
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = [])
{
$macros = $this->macros;
echo twig_escape_filter($this->env, ($context["title"] ?? null), "html", null, true);
}
// line 5
public function block_content($context, array $blocks = [])
{
$macros = $this->macros;
// line 6
echo " <h1 class=\"display-4\">";
echo twig_escape_filter($this->env, ($context["title"] ?? null), "html", null, true);
echo "</h1>
";
// line 7
echo twig_escape_filter($this->env, $this->env->getFunction('create_form')->getCallable()(), "html", null, true);
echo "
";
}
/**
* @codeCoverageIgnore
*/
public function getTemplateName()
{
return "form/form.html.twig";
}
/**
* @codeCoverageIgnore
*/
public function isTraitable()
{
return false;
}
/**
* @codeCoverageIgnore
*/
public function getDebugInfo()
{
return array ( 63 => 7, 58 => 6, 54 => 5, 47 => 3, 36 => 1,);
}
public function getSourceContext()
{
return new Source("", "form/form.html.twig", "/home/kali/php/untitled/views/form/form.html.twig");
}
}

View File

@ -0,0 +1,103 @@
<?php
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Source;
use Twig\Template;
/* layouts/simple.html.twig */
class __TwigTemplate_e48551b2ca758109aa7de7556ee07a2e extends Template
{
private $source;
private $macros = [];
public function __construct(Environment $env)
{
parent::__construct($env);
$this->source = $this->getSourceContext();
$this->parent = false;
$this->blocks = [
'title' => [$this, 'block_title'],
'content' => [$this, 'block_content'],
];
}
protected function doDisplay(array $context, array $blocks = [])
{
$macros = $this->macros;
// line 1
echo "<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<title>";
// line 5
$this->displayBlock('title', $context, $blocks);
echo " </title>
<link rel=\"stylesheet\" href=\"vendor/twbs/bootstrap/dist/css/bootstrap.css\">
<link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\"
integrity=\"sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN\" crossorigin=\"anonymous\" />
</head>
<body>
<div class=\"container\">
<div class=\"row\">
<div class=\"col-12\">
";
// line 15
$this->displayBlock('content', $context, $blocks);
// line 16
echo " </div>
</div>
</div>
</body>
</html>";
}
// line 5
public function block_title($context, array $blocks = [])
{
$macros = $this->macros;
}
// line 15
public function block_content($context, array $blocks = [])
{
$macros = $this->macros;
}
/**
* @codeCoverageIgnore
*/
public function getTemplateName()
{
return "layouts/simple.html.twig";
}
/**
* @codeCoverageIgnore
*/
public function getDebugInfo()
{
return array ( 78 => 15, 72 => 5, 60 => 16, 58 => 15, 45 => 5, 39 => 1,);
}
public function getSourceContext()
{
return new Source("", "layouts/simple.html.twig", "/home/kali/php/untitled/views/layouts/simple.html.twig");
}
}

View File

@ -0,0 +1,102 @@
<?php
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Source;
use Twig\Template;
/* form/result.html.twig */
class __TwigTemplate_e631c8331e0b3314f0fca4478f143546 extends Template
{
private $source;
private $macros = [];
public function __construct(Environment $env)
{
parent::__construct($env);
$this->source = $this->getSourceContext();
$this->blocks = [
'title' => [$this, 'block_title'],
'content' => [$this, 'block_content'],
];
}
protected function doGetParent(array $context)
{
// line 1
return "layouts/simple.html.twig";
}
protected function doDisplay(array $context, array $blocks = [])
{
$macros = $this->macros;
$this->parent = $this->loadTemplate("layouts/simple.html.twig", "form/result.html.twig", 1);
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = [])
{
$macros = $this->macros;
echo twig_escape_filter($this->env, ($context["title"] ?? null), "html", null, true);
}
// line 5
public function block_content($context, array $blocks = [])
{
$macros = $this->macros;
// line 6
echo " <h1 class=\"display-4\">";
echo twig_escape_filter($this->env, ($context["title"] ?? null), "html", null, true);
echo "</h1>
";
// line 8
echo twig_escape_filter($this->env, $this->env->getFunction('create_table')->getCallable()(), "html", null, true);
echo "
";
// line 9
echo twig_escape_filter($this->env, $this->env->getFunction('create_pagination')->getCallable()(), "html", null, true);
echo "
";
}
/**
* @codeCoverageIgnore
*/
public function getTemplateName()
{
return "form/result.html.twig";
}
/**
* @codeCoverageIgnore
*/
public function isTraitable()
{
return false;
}
/**
* @codeCoverageIgnore
*/
public function getDebugInfo()
{
return array ( 68 => 9, 64 => 8, 58 => 6, 54 => 5, 47 => 3, 36 => 1,);
}
public function getSourceContext()
{
return new Source("", "form/result.html.twig", "/home/kali/php/untitled/views/form/result.html.twig");
}
}

View File

@ -18,6 +18,7 @@
"twig/twig": "^3.0",
"illuminate/database": "^11.0",
"vlucas/phpdotenv": "^5.6",
"illuminate/filesystem": "^11.1"
"illuminate/filesystem": "^11.1",
"rakit/validation": "^1.4"
}
}

48
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "8425ba8fa8c3256af1097d721de637ad",
"content-hash": "4e0167cc51d61bb5064d445b684aefae",
"packages": [
{
"name": "brick/math",
@ -1150,6 +1150,52 @@
},
"time": "2021-10-29T13:26:27+00:00"
},
{
"name": "rakit/validation",
"version": "v1.4.0",
"source": {
"type": "git",
"url": "https://github.com/rakit/validation.git",
"reference": "ff003a35cdf5030a5f2482299f4c93f344a35b29"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/rakit/validation/zipball/ff003a35cdf5030a5f2482299f4c93f344a35b29",
"reference": "ff003a35cdf5030a5f2482299f4c93f344a35b29",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"php": ">=7.0"
},
"require-dev": {
"php-coveralls/php-coveralls": "^2.2",
"phpunit/phpunit": "^6.5",
"squizlabs/php_codesniffer": "^3"
},
"type": "library",
"autoload": {
"psr-4": {
"Rakit\\Validation\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Muhammad Syifa",
"email": "emsifa@gmail.com"
}
],
"description": "PHP Laravel like standalone validation library",
"support": {
"issues": "https://github.com/rakit/validation/issues",
"source": "https://github.com/rakit/validation/tree/v1.4.0"
},
"time": "2020-08-27T05:07:01+00:00"
},
{
"name": "symfony/clock",
"version": "v7.0.5",

View File

@ -34,6 +34,7 @@ $router->get("/admin/create-form", [\itguild\forms\app\controllers\AdminControll
$router->post("/admin/save-form", [\itguild\forms\app\controllers\AdminController::class, "saveFormAction"]);
$router->get("/admin/form-add-fields", [\itguild\forms\app\controllers\AdminController::class, "getFormAddFieldsAction"]);
$router->get("/admin/set-value-select", [\itguild\forms\app\controllers\AdminController::class, "getSelectValue"]);
$router->get("/admin/edit-form/{id}", [\itguild\forms\app\controllers\AdminController::class, "editFormAction"]);
$dispatcher = new Phroute\Phroute\Dispatcher($router->getData());
$response = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

21
src/app/DTO/FormDTO.php Normal file
View File

@ -0,0 +1,21 @@
<?php
namespace itguild\forms\app\DTO;
use itguild\forms\app\core\CGDTO;
use itguild\forms\debug\Debug;
class FormDTO extends CGDTO
{
public string $title;
public $perPage;
public string $view;
public string $edit;
public string $delete;
protected array $fillable = [
'title', 'perPage', 'view', 'edit', 'delete'
];
}

View File

@ -5,20 +5,31 @@ namespace itguild\forms\app\controllers;
use Illuminate\Database\Events\DatabaseBusy;
use itguild\forms\ActiveForm;
use itguild\forms\app\core\BaseController;
use itguild\forms\app\DTO\FormDTO;
use itguild\forms\app\models\FormInputModel;
use itguild\forms\app\models\FormModel;
use itguild\forms\app\models\InputTypeModel;
use itguild\forms\app\models\InputValueModel;
use itguild\forms\app\requests\CreateFormRequest;
use itguild\forms\core\cg_view\CgView;
/**
* @var \itguild\forms\ActiveForm $form ;
* @var \itguild\forms\ActiveForm $form ;
*/
use itguild\forms\core\CgRequest;
use itguild\forms\debug\Debug;
use itguild\forms\exceptions\CreateFormException;
use itguild\forms\exceptions\FieldTypeNotFound;
use itguild\forms\exceptions\FormNotFoundException;
use itguild\forms\Form;
use itguild\forms\helpers\TranslitorHelper;
use itguild\forms\inputs\Select;
use itguild\forms\inputs\TextInput;
use itguild\forms\inputs\TextArea;
use itguild\forms\JsonForm;
use Twig\TwigFunction;
class AdminController extends BaseController
{
@ -27,35 +38,95 @@ class AdminController extends BaseController
public function createAction(): void
{
$this->cgView->layout = "/layouts/admin_layout.php";
$this->cgView->render("/admin/index.php", ['title' => "Создать форму", 'form' => new ActiveForm()]);
$this->cgView->render("/admin/index.php", [
'title' => "Редактировать форму",
'form' => new ActiveForm(),
'dto' => new FormDTO(),
]);
}
/**
* @throws CreateFormException
*/
public function saveFormAction(): void
{
$request = new CreateFormRequest();
if (!$request->validate()) {
$title = $_POST["title"];
$perPage = $_POST['perPage'];
$inputs = $_POST["InputForm"];
$inputArray = [];
foreach ($inputs as $input){
$form = FormInputModel::Create(['form_id' => 42, 'input_type_id' => $input['type'], 'label' => $input['name'], 'name' => 'adsads', 'params' => "adsasd"]);
Debug::prn($form);
throw new CreateFormException("Validation error");
}
$title = $request->post('title');
$perPage = $request->post('perPage', 10);
$inputs = $request->post('InputForm', []);
$actionView = $request->post("actionView");
$actionEdit = $request->post("actionEdit");
$actionDelete = $request->post("actionDelete");
$actions = [$actionView, $actionEdit, $actionDelete];
$resultArray = ['meta' => ['perpage' => $perPage, 'status' => "1", 'actions' => $actions], 'params' => ['class' => "form-control", 'id' => 'form']];
$form = FormModel::Create(['title' => $title, 'status' => FormModel::STATUS_ACTIVE, 'params' => json_encode($resultArray, true)]);
foreach ($inputs as $input) {
$name = TranslitorHelper::translit($input['name']);
$params = [
"name" => $name,
"class" => "form-control",
];
if ($input['type'] == InputTypeModel::RADIO_TYPE) {
$radio = explode("\n", $input['radio']);
foreach ($radio as $key) {
$nameRadio = TranslitorHelper::translit($key);
$paramsRadio = [
"name" => $name,
"value" => $key,
'label' => ['title' => $key, 'for' => $key, "class" => 'form-label']
];
$formInput = FormInputModel::Create([
'form_id' => $form->id,
'input_type_id' => $input['type'],
'label' => $key,
'name' => $name,
'params' => json_encode($paramsRadio)
]);
}
} else {
$formInput = FormInputModel::Create([
'form_id' => $form->id,
'input_type_id' => $input['type'],
'label' => $name,
'name' => $name,
'params' => json_encode($params)
]);
}
$resultArray = ['meta' => ['perpage' => $perPage]];
if ($input['type'] == InputTypeModel::SELECT_TYPE) {
$options = explode("\n", $input['options']);
foreach ($options as $option) {
InputValueModel::Create(['form_input_id' => $formInput->id, 'value' => $option]);
}
}
Debug::prn(json_encode($resultArray, true));
}
//if (isset($title) and isset($params)) {
// $form = FormModel::Create(['title' => $title, 'status' => FormModel::STATUS_ACTIVE, 'params' => json_encode($resultArray, true)]);
// echo "Форма сохранена!";
//}//
$this->redirect("/form-result/$form->id");
}
public function getFormAddFieldsAction(): void
{
$this->cgView->render("/admin/_form_add_fields_ajax.php", ['form' => new ActiveForm()]);
}
public function getSelectValue(): void
{
$selectValue = $_GET["value"];
@ -73,13 +144,44 @@ class AdminController extends BaseController
$viewName = $fields[$selectValue] ?? false;
if (!$viewName){
if (!$viewName) {
throw new FieldTypeNotFound($selectValue);
}
$this->cgView->render("/admin/field_type/$viewName.php", ['form' => new ActiveForm(), 'count' => $countInput]);
}
public function editFormAction($id)
{
$form = FormModel::find($id)->toArray();
$dto = new FormDTO();
$formArr = json_decode($form['params'], true);
$fillableRes = [];
$fillableRes['title'] = $form['title'];
foreach ($formArr['meta'] as $key => $value){
if($key == 'perpage'){
$fillableRes['perPage'] = (string)$value;
}
else if($key == "actions"){
foreach ($value as $item){
$fillableRes[$item] = $item;
}
}
}
$dto->load($fillableRes);
if (!$form) {
throw new FormNotFoundException($id);
}
$this->cgView->layout = "/layouts/admin_layout.php";
$this->cgView->render("/admin/index.php", [
'title' => "Редактировать форму",
'form' => new ActiveForm(),
'dto' => $dto,
]);
}

View File

@ -5,6 +5,7 @@ namespace itguild\forms\app\controllers;
use itguild\forms\app\core\BaseController;
use itguild\forms\app\models\FormModel;
use itguild\forms\app\models\FormResModel;
use itguild\forms\app\models\InputTypeModel;
use itguild\forms\app\models\InputValueModel;
use itguild\forms\debug\Debug;
use itguild\forms\exceptions\FormNotFoundException;
@ -91,7 +92,7 @@ class FormController extends BaseController
$fillable = $formParams["meta"]["fillable"] ?? null;
$actions = $formParams["meta"]["actions"] ?? null;
$offset = ($page - 1) * $perPage;
$countItems = FormResModel::where("status", 1)->count();
$countItems = FormResModel::where("status", 1)->where("form_id", $form->id)->count();
$table = FormResModel::where("form_id", $id)->where("status", FormResModel::STATUS_ACTIVE)->limit(3)->offset($offset)->get();
foreach ($table as $key => $item) {
@ -306,24 +307,24 @@ class FormController extends BaseController
$options[$value['id']] = $value['value'];
}
}
//Debug::dd($field->params);
if ($field->params) {
$fieldArr = array_merge($fieldArr, json_decode($field->params, true));
}
$fieldArr['name'] = $field->name ?? $fieldArr['name'];
if ($field->input_type_id === 4) {
if ($resArr[$fieldArr['name']] === $fieldArr['value']) {
if ($field->input_type_id === InputTypeModel::RADIO_TYPE) {
if (isset($resArr[$fieldArr['name']]) && $resArr[$fieldArr['name']] === $fieldArr['value']) {
$fieldArr['checked'] = "true";
}
}
if ($field->input_type_id === 1) {
if ($resArr[$fieldArr['name']] === $fieldArr['value']) {
if ($field->input_type_id === InputTypeModel::CHECKBOX_TYPE) {
if (isset($resArr[$fieldArr['name']]) && $resArr[$fieldArr['name']] === $fieldArr['value']) {
$fieldArr['checked'] = "true";
}
}
if ($formResult && $field->input_type_id !== 4) {
if ($formResult && $field->input_type_id !== InputTypeModel::RADIO_TYPE) {
$fieldArr['value'] = $resArr[$fieldArr['name']] ?? null;
}
$fieldArr['type'] = $field->inputType['type'] ? $field->inputType['type'] : "textInput";

View File

@ -3,6 +3,7 @@
namespace itguild\forms\app\core;
use itguild\forms\core\cg_view\CgView;
use JetBrains\PhpStorm\NoReturn;
class BaseController
{
@ -21,4 +22,10 @@ class BaseController
$this->cgView->viewPath = VIEW_PATH;
}
#[NoReturn] protected function redirect(string $url, int $code = 301): void
{
header('Location: ' . $url, true, $code);
exit;
}
}

33
src/app/core/CGDTO.php Normal file
View File

@ -0,0 +1,33 @@
<?php
namespace itguild\forms\app\core;
use itguild\forms\debug\Debug;
class CGDTO
{
protected array $fillable = [];
public function load(array $params): void
{
foreach ($this->fillable as $item) {
if (isset($params[$item])) {
$this->$item = $params[$item];
}
}
}
public function get(string $name)
{
if (!empty($this->$name))
{
return $this->$name;
}
return null;
}
}

View File

@ -6,6 +6,13 @@ use Illuminate\Database\Eloquent\Model;
class InputTypeModel extends Model
{
const SELECT_TYPE = 6;
const INPUT_TEXT_TYPE = 2;
const TEXT_AREA_TYPE = 3;
const BUTTON_TYPE = 5;
const CHECKBOX_TYPE = 1;
const RADIO_TYPE = 4;
protected $table = "input_type";
protected $fillable = [

View File

@ -0,0 +1,19 @@
<?php
namespace itguild\forms\app\requests;
use itguild\forms\core\CgRequest;
class CreateFormRequest extends CgRequest
{
public function rules(): array
{
return [
'title' => 'required|min:5',
'perPage' => 'numeric',
'InputForm' => 'required|array',
];
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace itguild\forms\app\services;
class InputTypeService
{
/**
* @return mixed
*/
public static function getInputTypes(): array
{
return \itguild\forms\app\models\InputTypeModel::where("status", 1)->pluck('name', 'id')->toArray();
}
}

226
src/core/CgRequest.php Normal file
View File

@ -0,0 +1,226 @@
<?php
namespace itguild\forms\core;
use AllowDynamicProperties;
use Rakit\Validation\Validator;
#[AllowDynamicProperties]
class CgRequest
{
/**
* @var string $host Абсолютный адрес сервера
*/
public $host;
/**
* @var array $headers Заголовки запроса
*/
public $headers;
/**
* @var array
*/
public $data = [];
/**
* @var array
*/
public $errors = [];
public function __construct()
{
$this->headers = $this->getRequestHeaders();
$this->load();
}
/**
* @return array
*/
public function rules()
{
return [];
}
/**
* @return array
*/
public function messages()
{
return [];
}
/**
* Возвращает абсолютный адрес сервера.
* @return string
*/
public function getHost(): string
{
if ($this->host !== null) {
return $this->host;
}
$http = $this->getIsSecure() ? 'https' : 'http';
if ($this->headerExist('Host')) {
$this->host = $http . '://' . $this->getHeader('Host');
} elseif (isset($_SERVER['SERVER_NAME'])) {
$this->host = $http . '://' . $_SERVER['SERVER_NAME'];
}
return $this->host;
}
/**
* Возвращает true если шифрование https, иначе false.
* @return bool
*/
public function getIsSecure(): bool
{
if (isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)) {
return true;
}
return false;
}
/**
* Проверяет был ли передан заголовок запроса.
* @return bool
*/
public function headerExist($header): bool
{
return isset($this->headers[$header]);
}
/**
* Возвращает заголовок запроса
* @param string $header Заголовок.
* @param mixed $defaultValue Значение если, параметр не передан.
* @return mixed|null
*/
public function getHeader($header, $defaultValue = null)
{
return $this->headers[$header] ?? $defaultValue;
}
/**
* Возвращает GET - параметр.
* @param string $param Параметр.
* @param mixed $defaultValue Значение если, параметр не передан.
* @return mixed
*/
public function get($param = null, $defaultValue = null)
{
if (is_null($param)) {
return $_GET;
}
return $_GET[$param] ?? $defaultValue;
}
/**
* Возвращает POST - параметр.
* @param string $param Параметр.
* @param mixed $defaultValue Значение если, параметр не передан.
* @return mixed
*/
public function post($param = null, $defaultValue = null)
{
if (is_null($param)) {
return $_POST;
}
return $_POST[$param] ?? $defaultValue;
}
/**
* Был ли POST - запрос.
* @return bool
*/
public function isPost(): bool
{
return ($_SERVER['REQUEST_METHOD'] === 'POST');
}
/**
* Был ли GET - запрос.
* @return bool
*/
public function isGet(): bool
{
return ($_SERVER['REQUEST_METHOD'] === 'GET');
}
/**
* Загружаем свойсва
*/
public function load(): void
{
if (!empty($_REQUEST)) {
foreach ($_REQUEST as $key => $item) {
$this->{$key} = $item;
$this->data[$key] = $item;
}
}
}
/**
* @return bool
*/
public function validate()
{
if (!empty($this->data)) {
$valid = new Validator();
$validation = $valid->make($this->data, $this->rules());
$validation->setMessages($this->messages());
$validation->validate();
if ($validation->fails()) {
$this->errors = $validation->errors();
return false;
}
}
return true;
}
/**
* @return array
*/
public function getMessagesArray()
{
$msgs = [];
if($this->errors){
foreach ($this->errors->toArray() as $item){
$msgs[] = array_values($item)[0];
}
}
return $msgs;
}
/**
* @return array
*/
protected function getRequestHeaders()
{
$headers = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
return $headers;
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace itguild\forms\exceptions;
class CreateFormException extends \Exception
{
function __construct(string $msg)
{
$this->message = "Create form error: " . $msg;
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace itguild\forms\helpers;
class TranslitorHelper
{
public static function translit($str){
$russian = array('А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З',
'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У',
'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я',
'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к',
'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц',
'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я');
$translit = array('A', 'B', 'V', 'G', 'D', 'E', 'E', 'Gh', 'Z',
'I', 'Y', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F',
'H', 'C', 'Ch', 'Sh', 'Sch', 'Y', 'Y', 'Y', 'E', 'Yu', 'Ya', 'a',
'b', 'v', 'g', 'd', 'e', 'e', 'gh', 'z', 'i', 'y', 'k', 'l', 'm',
'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'sch',
'y', 'y', 'y', 'e', 'yu', 'ya');
return str_replace($russian, $translit, $str);
}
}

View File

@ -121,9 +121,14 @@ class ListJsonTable
return false;
}
private function is_fillable($column)
private function is_fillable($column): bool
{
if (in_array($column, $this->data['meta']['fillable'])) {
if (isset($this->data['meta']['fillable'])){
if (in_array($column, $this->data['meta']['fillable'])) {
return true;
}
}
else{
return true;
}

View File

@ -3,6 +3,7 @@
/**
*
* @var \itguild\forms\ActiveForm $form
* @var integer $count
*
*/

View File

@ -3,6 +3,7 @@
/**
*
* @var \itguild\forms\ActiveForm $form
* @var integer $count
*
*/
@ -11,5 +12,8 @@ use itguild\forms\inputs\TextInput;
$form->field(TextInput::class, name: "InputForm[$count][name]", params: ['class' => "form-control",
'placeholder' => "Наименование"])->setLabel("Наименование (например \"Телефон\")")->render();
$form->field(\itguild\forms\inputs\TextArea::class, name: "InputForm[$count][radio]", params: ['class' => "form-control"])
->setLabel("Введите радио кнопки, каждую на новой строке")
->render();
$form->field(Checkbox::class, name: "InputForm[$count][required]", params:['value' => '1'])->setLabel("Обязательное")->render();
$form->field(\itguild\forms\inputs\Hidden::class, name: "InputForm[$count][type]", params: ['value' => '4'])->render();

View File

@ -3,6 +3,7 @@
/**
*
* @var \itguild\forms\ActiveForm $form
* @var integer $count
*
*/
@ -12,9 +13,9 @@ use itguild\forms\inputs\TextInput;
$form->field(TextInput::class, name: "InputForm[$count][name]", params: ['class' => "form-control",
'placeholder' => "Наименование"])->setLabel("Наименование (например \"Телефон\")")->render();
'placeholder' => "Наименование"])->setLabel("Наименование (например \"Список городов\")")->render();
$form->field(TextArea::class, name: "InputForm[$count][options]", params: ['class' => "form-control"])
->setLabel("Опции выпадающего списка")
->setLabel("Опции выпадающего списка, каждый с новой строки")
->render();
$form->field(Checkbox::class, name: "InputForm[$count][required]", params:['value' => '1'])->setLabel("Обязательное")->render();
$form->field(\itguild\forms\inputs\Hidden::class, name: "InputForm[$count][type]", params: ['value' => '6'])->render();

View File

@ -3,9 +3,9 @@
/**
*
* @var \itguild\forms\ActiveForm $form
* @var integer $count
*
*/
use itguild\forms\inputs\Checkbox;
use itguild\forms\inputs\TextInput;

View File

@ -1,41 +1,67 @@
<?php
/**
* @var \itguild\forms\ActiveForm $form ;
* @var \itguild\forms\ActiveForm $form
* @var \itguild\forms\app\DTO\FormDTO $dto
*/
use itguild\forms\inputs\TextInput;
use itguild\forms\inputs\TextArea;
$types = \itguild\forms\app\models\InputTypeModel::where("status", 1)->pluck('name', 'id')->toArray();
?>
<?php echo $form->beginForm("/admin/save-form"); ?>
<?php $form->field(TextInput::class, name: "title", params: [
'class' => "form-control",
'placeholder' => 'Название формы'
'placeholder' => 'Название формы',
'value' => $dto->get('title'),
])
->setLabel("Название формы")
->render();
$form->field(TextInput::class, name: "perPage", params: [
'class' => "form-control",
'placeholder' => 'Perpage'
'placeholder' => 'Perpage',
'value' => $dto->get('perPage'),
])
->setLabel("Количество выводимых записей на страницу")
->render();
$form->field(\itguild\forms\inputs\Checkbox::class, name: "actionView", params: [
'value' => 'view',
'checked' => $dto->get('view')
])
->setLabel("Разрешить просмотр")
->render();
$form->field(\itguild\forms\inputs\Checkbox::class, name: "actionEdit", params: [
'value' => 'edit',
'checked' => $dto->get('edit')
])
->setLabel("Разрешить редактирование")
->render();
$form->field(\itguild\forms\inputs\Checkbox::class, name: "actionDelete", params: [
'value' => 'delete',
'checked' => $dto->get('delete')
])
->setLabel("Разрешить удаление")
->render();
$form->field(\itguild\forms\inputs\Select::class, name: "inputType", params: [
'class' => "form-control-sm",
'id' => "selectID",
'placeholder' => 'Параметры',
'options' => $types
'options' => \itguild\forms\app\services\InputTypeService::getInputTypes()
])
->setLabel("Добавить поле")
->render();
?>
<button style="margin-top:15px" type="button" id="buttonAdd" class="btn btn-success " onclick="getValueSelect()" data-count=0>Добавить поле</button>
<button style="margin-top:15px" type="button" id="buttonAdd" class="btn btn-success " onclick="getValueSelect()"
data-count=0>Добавить поле
</button>
<?php