HummingBirdAnimeClient/src/AnimeClient/FormGenerator.php

112 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?php declare(strict_types=1);
/**
* Hummingbird Anime List Client
*
* An API client for Kitsu to manage anime and manga watch lists
*
2023-07-13 11:08:05 -04:00
* PHP version 8.1
*
2023-07-13 11:08:05 -04:00
* @copyright 2015 - 2023 Timothy J. Warren <tim@timshome.page>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2020-12-10 17:06:50 -05:00
* @version 5.2
2023-07-13 11:08:05 -04:00
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient;
2019-12-09 14:34:23 -05:00
use Aura\Html\HelperLocator;
use Aviat\Ion\Di\ContainerInterface;
use Aviat\Ion\Di\Exception\{ContainerException, NotFoundException};
/**
* Helper object to manage form generation, especially for config editing
*/
final class FormGenerator
{
/**
* Html generation helper
*/
2020-04-10 20:01:46 -04:00
private HelperLocator $helper;
2018-11-09 10:38:35 -05:00
/**
* FormGenerator constructor.
*
2019-12-09 14:34:23 -05:00
* @throws ContainerException
* @throws NotFoundException
2018-11-09 10:38:35 -05:00
*/
private function __construct(ContainerInterface $container)
{
$this->helper = $container->get('html-helper');
}
/**
* Create a new FormGenerator
*/
public static function new(ContainerInterface $container): self
{
2020-12-11 15:37:55 -05:00
return new self($container);
}
/**
* Generate the html structure of the form
*/
2018-11-09 10:38:35 -05:00
public function generate(string $name, array $form): string
{
$type = $form['type'];
2020-03-12 12:32:32 -04:00
$display = $form['display'] ?? TRUE;
2020-12-11 14:26:54 -05:00
$value = $form['value'] ?? $form['default'] ?? '';
2020-03-12 12:32:32 -04:00
if ($display === FALSE)
{
return (string) $this->helper->input([
'type' => 'hidden',
'name' => $name,
2020-03-12 12:32:32 -04:00
'value' => $value,
]);
}
$params = [
'name' => $name,
2020-03-12 12:32:32 -04:00
'value' => $value,
'attribs' => [
'id' => $name,
],
];
switch ($type)
{
case 'boolean':
$params['type'] = 'radio';
$params['options'] = [
'1' => 'Yes',
'0' => 'No',
];
$params['strict'] = TRUE;
unset($params['attribs']['id']);
2023-05-09 12:52:11 -04:00
break;
case 'string':
$params['type'] = 'text';
2023-05-09 12:52:11 -04:00
break;
case 'select':
$params['type'] = 'select';
$params['options'] = array_flip($form['options']);
2023-05-09 12:52:11 -04:00
break;
2020-04-10 20:01:46 -04:00
default:
break;
}
foreach (['readonly', 'disabled'] as $key)
{
2020-03-12 12:32:32 -04:00
if (array_key_exists($key, $form) && $form[$key] !== FALSE)
{
$params['attribs'][$key] = $form[$key];
}
}
return (string) $this->helper->input($params);
}
}