Skip to content

Commit

Permalink
WIP: take over...
Browse files Browse the repository at this point in the history
  • Loading branch information
lippserd committed Nov 9, 2022
1 parent 5d6f095 commit 7d617be
Showing 1 changed file with 19 additions and 33 deletions.
52 changes: 19 additions & 33 deletions src/FormElement/SelectElement.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

use Closure;
use ipl\Html\Attributes;
use ipl\Html\Common\MultipleAttribute;
use ipl\Html\Html;
use ipl\Html\HtmlElement;
use ipl\Validator\DeferredInArrayValidator;

class SelectElement extends BaseFormElement
{
use MultipleAttribute;

protected $tag = 'select';

/** @var SelectOption[] */
Expand All @@ -24,32 +27,6 @@ class SelectElement extends BaseFormElement
/** @var array|string Array when the attribute `multiple` is set to true, string otherwise */
protected $value;

/** @var bool Whether the attribute `multiple` is set to true */
protected $isMultiSelect;

public function __construct($name, $attributes = null)
{
if (is_array($attributes)) { // because attributes can be in any order
$this->isMultiSelect = in_array('multiple', $attributes) && $attributes['multiple'] === true;
} elseif ($attributes instanceof Attributes) {
$this->isMultiSelect = $attributes->get('multiple')->getValue() === true;
}

$this->getAttributes()->registerAttributeCallback(
'options',
null,
[$this, 'setOptions']
);
// ZF1 compatibility:
$this->getAttributes()->registerAttributeCallback(
'multiOptions',
null,
[$this, 'setOptions']
);

parent::__construct($name, $attributes);
}

public function getValueAttribute()
{
// select elements don't have a value attribute
Expand All @@ -58,7 +35,7 @@ public function getValueAttribute()

public function getNameAttribute()
{
if ($this->isMultiSelect) {
if ($this->isMultiple()) {
return $this->getName() . '[]';
}

Expand All @@ -69,11 +46,7 @@ public function getValue()
{
$value = parent::getValue();

if ($this->isMultiSelect) {
return (array) $value;
}

return $value;
return $this->isMultiple() ? (array) $value : $value;
}

/**
Expand Down Expand Up @@ -212,7 +185,7 @@ protected function makeOption($value, $label)
*/
protected function isSelectedOption($optionValue): bool
{
if ($this->isMultiSelect) {
if ($this->isMultiple()) {
return in_array($optionValue, $this->getValue(), ! is_int($optionValue));
}

Expand All @@ -227,4 +200,17 @@ protected function assemble()
{
$this->addHtml(...array_values($this->optionContent));
}

protected function registerAttributeCallbacks(Attributes $attributes)
{
parent::registerAttributeCallbacks($attributes);

$attributes->registerAttributeCallback(
'options',
null,
[$this, 'setOptions']
);

$this->registerMultipleAttributeCallback($attributes);
}
}

0 comments on commit 7d617be

Please sign in to comment.