Skip to content

Commit

Permalink
Refactor: Extract finding <option>s in DOM to helper
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed Apr 5, 2020
1 parent faf9fa3 commit 5edf00c
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/main/php/unittest/web/SelectField.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,31 @@
*/
class SelectField extends Field {

/** @return DOMElement[] */
private function options() {
$r= [];
foreach ($this->node->childNodes as $child) {
if ($child instanceof \DOMElement && 'option' === $child->tagName) $r[]= $child;
}
return $r;
}

/**
* Get this field's value
*
* @return string
*/
public function getValue() {
if (!$this->node->hasChildNodes()) return null;
$options= $this->options();
if (empty($options)) return null;

// Find selected
foreach ($this->node->childNodes as $child) {
if (!($child instanceof \DOMElement) || 'option' !== $child->tagName || !$child->hasAttribute('selected')) continue;
return $child->getAttribute('value');
foreach ($options as $option) {
if ($option->hasAttribute('selected')) return $option->getAttribute('value');
}

// Use first child's value
return $this->node->childNodes->item(0)->getAttribute('value');
return $options[0]->getAttribute('value');
}

/**
Expand All @@ -33,9 +42,8 @@ public function getValue() {
*/
public function getOptions() {
$r= [];
foreach ($this->node->childNodes as $child) {
if (!($child instanceof \DOMElement) || 'option' !== $child->tagName) continue;
$r[]= new SelectOption($this->form, $child);
foreach ($this->options() as $option) {
$r[]= new SelectOption($this->form, $option);
}
return $r;
}
Expand All @@ -47,9 +55,8 @@ public function getOptions() {
*/
public function getSelectedOptions() {
$r= [];
foreach ($this->node->childNodes as $child) {
if (!($child instanceof \DOMElement) || 'option' !== $child->tagName || !$child->hasAttribute('selected')) continue;
$r[]= new SelectOption($this->form, $child);
foreach ($this->options() as $option) {
$option->hasAttribute('selected') && $r[]= new SelectOption($this->form, $option);
}
return $r;
}
Expand Down

0 comments on commit 5edf00c

Please sign in to comment.