71 lines
1.7 KiB
PHP
71 lines
1.7 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace Lewp\Forms;
|
||
|
|
|
||
|
|
class Torunn
|
||
|
|
{
|
||
|
|
|
||
|
|
private static $direct_inputs = [
|
||
|
|
'input'
|
||
|
|
];
|
||
|
|
|
||
|
|
private static $indirect_inputs = [
|
||
|
|
'select'
|
||
|
|
];
|
||
|
|
|
||
|
|
public static function fill(\DOMNode $form, array $data_array)
|
||
|
|
{
|
||
|
|
self::traverse($form, $data_array);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function traverse($node, array &$data, bool $recursive = true)
|
||
|
|
{
|
||
|
|
$children = $node->childNodes;
|
||
|
|
$children_count = count($children);
|
||
|
|
for ($i = 0; $i < $children_count; ++$i) {
|
||
|
|
$child = $children[$i];
|
||
|
|
|
||
|
|
if (in_array($child->tagName, self::$direct_inputs)) {
|
||
|
|
self::fillDirectInput($child, array_shift($data) ?? '');
|
||
|
|
continue;
|
||
|
|
//$child->setAttribute('value', array_shift($data) ?? 'empty');
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($child->tagName === 'select') {
|
||
|
|
self::fillSelectElement($child, array_shift($data) ?? '');
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($recursive) {
|
||
|
|
self::traverse($child, $data);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function fillDirectInput($node, $value)
|
||
|
|
{
|
||
|
|
if ($value === '') {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
$node->setAttribute('value', $value);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function fillSelectElement($node, $value)
|
||
|
|
{
|
||
|
|
if ($value === '') {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
$children = $node->childNodes;
|
||
|
|
foreach ($children as $child) {
|
||
|
|
if (($child->tagName === 'option')
|
||
|
|
&& ($child->getAttribute('value') === $value)
|
||
|
|
) {
|
||
|
|
$child->setAttribute('selected', 'selected');
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|