81 lines
2.3 KiB
PHP
81 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace Picea\Ui\Form;
|
|
|
|
use Picea\Ui\Common\UiElement;
|
|
use Picea\Extension\Extension;
|
|
use Picea\Extension\ExtensionTrait;
|
|
|
|
class UiSelect extends UiElement implements Extension {
|
|
use ExtensionTrait;
|
|
|
|
public string $token = "ui.select";
|
|
|
|
public string $tag = "select";
|
|
|
|
public array $attributes = [
|
|
'class' => 'ui-select',
|
|
];
|
|
|
|
public function parse(/*\Picae\Compiler\Context*/ &$context, ?string $arguments, string $token) : string
|
|
{
|
|
return "<?php echo ( new \\" . static::class . "() )->buildHtml($arguments) ?>";
|
|
}
|
|
|
|
public function buildHtml(string $name, array $list, $value = null, array $attributes = [], bool $strictComparison = true) : string
|
|
{
|
|
$this->attributes([ 'name' => $name ] + $attributes + $this->attributes);
|
|
$this->setList($list, $value, $strictComparison);
|
|
|
|
return $this->render();
|
|
}
|
|
|
|
protected function setValue($value) : void
|
|
{
|
|
$this->attributes['value'] = $value;
|
|
}
|
|
|
|
protected function setList(array $list, $selected, bool $strict = true) : void
|
|
{
|
|
foreach($list as $key => $item) {
|
|
|
|
if ($item instanceof UiElement) {
|
|
$this->append($item);
|
|
|
|
continue;
|
|
}
|
|
elseif ( is_array($item) ) {
|
|
$obj = new UiElement("optgroup");
|
|
$obj->attributes(['label' => $key]);
|
|
|
|
foreach($item as $subKey => $subItem) {
|
|
$obj->append($this->createOption($subItem, $subKey, $this->isSelected($subKey, $selected, $strict)));
|
|
}
|
|
}
|
|
else {
|
|
$obj = $this->createOption($item, $key, $this->isSelected($key, $selected, $strict));
|
|
}
|
|
|
|
$this->append($obj);
|
|
}
|
|
}
|
|
|
|
protected function createOption(string $name, string $value, bool $selected, array $attributes = []) : UiElement
|
|
{
|
|
$option = new UiElement("option");
|
|
$option->text($name);
|
|
$option->attributes($attributes + [ 'value' => $value ]);
|
|
|
|
if ($selected) {
|
|
$option->attributes(['selected' => 'selected']);
|
|
}
|
|
|
|
return $option;
|
|
}
|
|
|
|
protected function isSelected($check, $value, bool $strict = true) : bool
|
|
{
|
|
return $strict ? $check === $value : $check == $value;
|
|
}
|
|
}
|