forms/JsonForm.php
2024-05-28 17:10:06 +03:00

87 lines
2.0 KiB
PHP
Executable File

<?php
namespace itguild\forms\form;
use itguild\forms\form\builders\Builder;
use itguild\forms\form\builders\LabelBuilder;
use itguild\forms\form\mappers\JsonInputMapper;
use itguild\forms\form\traits\CreateParams;
class JsonForm
{
use CreateParams;
private $jsonData;
private $html = '';
public function __construct($json)
{
$this->jsonData = json_decode($json, true);
}
public function beginForm($params = []): string
{
$paramsString = $this->createParams($params);
return "<form $paramsString >";
}
public function endForm(): string
{
return "</form>";
}
public function convertHTML(): void
{
$this->html .= $this->beginForm($this->jsonData['meta']);
foreach ($this->jsonData['data'] as $item) {
if (isset($item["type"]) and isset($item["name"])) {
/**
* @var $builder Builder
*/
$builder = JsonInputMapper::getBuilder($item["type"]);
unset($item["type"]);
$name = $item["name"];
unset($item["name"]);
$label = '';
if (isset($item['label'])) {
$label = $this->createLabel($item['label']);
}
unset($item['label']);
$input = $builder::build($name, $item);
$input->setLabel($label)->create();
$this->html .= $input->fetch();
}
}
$this->html .= $this->endForm();
//return $this->fetch($html);
}
private function createLabel($labelParams)
{
$title = '';
if(isset($labelParams['title'])){
$title = $labelParams['title'];
unset($labelParams['title']);
}
return LabelBuilder::build($title, $labelParams);
}
public function render(): void
{
echo $this->html;
}
public function fetch(): string
{
return $this->html;
}
}