|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Zenstruck\Browser\Dom\Form\Field; |
|
4
|
|
|
|
|
5
|
|
|
use Facebook\WebDriver\Exception\NoSuchElementException; |
|
6
|
|
|
use Facebook\WebDriver\WebDriverSelect; |
|
7
|
|
|
use Symfony\Component\DomCrawler\Field\ChoiceFormField; |
|
8
|
|
|
use Symfony\Component\Panther\DomCrawler\Crawler as PantherCrawler; |
|
9
|
|
|
use Zenstruck\Browser\Dom\Form\Field; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @mixin ChoiceFormField |
|
13
|
|
|
* |
|
14
|
|
|
* @author Kevin Bond <[email protected]> |
|
15
|
|
|
*/ |
|
16
|
|
|
final class ChoiceField extends Field |
|
17
|
|
|
{ |
|
18
|
|
|
public function tick(): void |
|
19
|
|
|
{ |
|
20
|
|
|
if ($this->is('radio')) { |
|
21
|
|
|
$this->setValue(null); |
|
22
|
|
|
|
|
23
|
|
|
return; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
$this->inner->tick(); |
|
|
|
|
|
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function untick(): void |
|
30
|
|
|
{ |
|
31
|
|
|
if ($this->is('radio')) { |
|
32
|
|
|
throw new \InvalidArgumentException('Radio fields cannot be unchecked.'); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
$this->inner->untick(); |
|
|
|
|
|
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function setValue($value): void |
|
39
|
|
|
{ |
|
40
|
|
|
if ($this->is('radio')) { |
|
41
|
|
|
$value = $value ?? $this->attr('value'); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (null === $value) { |
|
45
|
|
|
throw new \InvalidArgumentException('Value required for select form fields.'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
if (\is_array($value) && !$this->isMultiple()) { |
|
|
|
|
|
|
49
|
|
|
throw new \InvalidArgumentException('Value for a single select form field cannot be an array.'); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
if (\is_array($value) && $this->isMultiple() && $this->dom->inner() instanceof PantherCrawler) { |
|
|
|
|
|
|
53
|
|
|
// todo have a separate PantherCrawler to avoid the "inner" check above |
|
54
|
|
|
// with panther, unselect all before setting (otherwise existing selections will remain) |
|
55
|
|
|
(new WebDriverSelect($this->dom->getElement(0)))->deselectAll(); |
|
|
|
|
|
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
try { |
|
59
|
|
|
$this->inner->setValue($value); |
|
60
|
|
|
} catch (NoSuchElementException $e) { |
|
61
|
|
|
// try selecting by visible text |
|
62
|
|
|
$select = new WebDriverSelect($this->dom->getElement(0)); |
|
63
|
|
|
|
|
64
|
|
|
foreach ((array) $value as $item) { |
|
65
|
|
|
$select->selectByVisibleText($item); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* @param array|string $type |
|
72
|
|
|
*/ |
|
73
|
|
|
public function is($type): bool |
|
74
|
|
|
{ |
|
75
|
|
|
return \in_array($this->getType(), (array) $type, true); |
|
|
|
|
|
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|