-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathSelenium2Driver.php
executable file
·1357 lines (1129 loc) · 41.4 KB
/
Selenium2Driver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the Behat\Mink.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Mink\Driver;
use Behat\Mink\Exception\DriverException;
use Behat\Mink\KeyModifier;
use Behat\Mink\Selector\Xpath\Escaper;
use WebDriver\Element;
use WebDriver\Exception\InvalidArgument;
use WebDriver\Exception\NoSuchElement;
use WebDriver\Exception\ScriptTimeout;
use WebDriver\Exception\StaleElementReference;
use WebDriver\Exception\Timeout;
use WebDriver\Exception\UnknownCommand;
use WebDriver\Exception\UnknownError;
use WebDriver\Key;
use WebDriver\Session;
use WebDriver\WebDriver;
use WebDriver\Window;
/**
* Selenium2 driver.
*
* @author Pete Otaqui <pete@otaqui.com>
*/
class Selenium2Driver extends CoreDriver
{
private const W3C_WINDOW_HANDLE_PREFIX = 'w3cwh:';
/**
* Whether the browser has been started
* @var bool
*/
private $started = false;
/**
* The WebDriver instance
* @var WebDriver
*/
private $webDriver;
/**
* @var string
*/
private $browserName;
/**
* @var array
*/
private $desiredCapabilities;
/**
* The WebDriverSession instance
* @var Session|null
*/
private $wdSession;
/**
* @var bool
*/
private $isW3C = false;
/**
* The timeout configuration
* @var array{script?: int, implicit?: int, page?: int}
*/
private $timeouts = array();
/**
* @var string|null
*/
private $initialWindowHandle = null;
/**
* @var Escaper
*/
private $xpathEscaper;
/**
* Instantiates the driver.
*
* @param string $browserName Browser name
* @param array|null $desiredCapabilities The desired capabilities
* @param string $wdHost The WebDriver host
*/
public function __construct(string $browserName = 'firefox', ?array $desiredCapabilities = null, string $wdHost = 'http://localhost:4444/wd/hub')
{
$this->setBrowserName($browserName);
$this->setDesiredCapabilities($desiredCapabilities);
$this->setWebDriver(new WebDriver($wdHost));
$this->xpathEscaper = new Escaper();
}
/**
* Sets the browser name
*
* @param string $browserName the name of the browser to start, default is 'firefox'
*
* @return void
*/
protected function setBrowserName(string $browserName = 'firefox')
{
$this->browserName = $browserName;
}
/**
* Sets the desired capabilities - called on construction. If null is provided, will set the
* defaults as desired.
*
* See http://code.google.com/p/selenium/wiki/DesiredCapabilities
*
* @param array|null $desiredCapabilities an array of capabilities to pass on to the WebDriver server
*
* @return void
*
* @throws DriverException
*/
public function setDesiredCapabilities(?array $desiredCapabilities = null)
{
if ($this->started) {
throw new DriverException("Unable to set desiredCapabilities, the session has already started");
}
if (null === $desiredCapabilities) {
$desiredCapabilities = array();
}
$desiredCapabilities['browserName'] = $this->browserName;
// Join $desiredCapabilities with defaultCapabilities
$desiredCapabilities = array_replace(self::getDefaultCapabilities(), $desiredCapabilities);
if (isset($desiredCapabilities['firefox'])) {
foreach ($desiredCapabilities['firefox'] as $capability => $value) {
switch ($capability) {
case 'profile':
$fileContents = file_get_contents($value);
if ($fileContents === false) {
throw new DriverException(sprintf('Could not read the profile file "%s".', $value));
}
$desiredCapabilities['firefox_'.$capability] = base64_encode($fileContents);
break;
default:
$desiredCapabilities['firefox_'.$capability] = $value;
}
}
unset($desiredCapabilities['firefox']);
}
// See https://sites.google.com/a/chromium.org/chromedriver/capabilities
if (isset($desiredCapabilities['chrome'])) {
$chromeOptions = (isset($desiredCapabilities['goog:chromeOptions']) && is_array($desiredCapabilities['goog:chromeOptions']))? $desiredCapabilities['goog:chromeOptions']:array();
foreach ($desiredCapabilities['chrome'] as $capability => $value) {
if ($capability == 'switches') {
$chromeOptions['args'] = $value;
} else {
$chromeOptions[$capability] = $value;
}
$desiredCapabilities['chrome.'.$capability] = $value;
}
$desiredCapabilities['goog:chromeOptions'] = $chromeOptions;
unset($desiredCapabilities['chrome']);
}
$this->desiredCapabilities = $desiredCapabilities;
}
/**
* Gets the desiredCapabilities
*
* @return array
*/
public function getDesiredCapabilities()
{
return $this->desiredCapabilities;
}
/**
* Sets the WebDriver instance
*
* @param WebDriver $webDriver An instance of the WebDriver class
*
* @return void
*/
public function setWebDriver(WebDriver $webDriver)
{
$this->webDriver = $webDriver;
}
/**
* Gets the WebDriverSession instance
*
* @return Session
*
* @throws DriverException if the session is not started
*/
public function getWebDriverSession()
{
if ($this->wdSession === null) {
throw new DriverException('The driver is not started.');
}
return $this->wdSession;
}
/**
* Returns the default capabilities
*
* @return array
*/
public static function getDefaultCapabilities()
{
return array(
'browserName' => 'firefox',
'name' => 'Behat Test',
);
}
/**
* Makes sure that the Syn event library has been injected into the current page,
* and return $this for a fluid interface,
*
* $this->withSyn()->executeJsOnXpath($xpath, $script);
*
* @return Selenium2Driver
*
* @throws DriverException
*/
protected function withSyn()
{
$hasSyn = $this->getWebDriverSession()->execute(array(
'script' => 'return window.syn !== undefined && window.syn.trigger !== undefined',
'args' => array()
));
if (!$hasSyn) {
$synJs = file_get_contents(__DIR__.'/Resources/syn.js');
\assert($synJs !== false);
$this->getWebDriverSession()->execute(array(
'script' => $synJs,
'args' => array()
));
}
return $this;
}
/**
* Creates some options for key events
*
* @param string|int $char the character or code
* @param KeyModifier::*|null $modifier
*
* @return string a json encoded options array for Syn
*
* @throws DriverException
*/
protected static function charToOptions($char, ?string $modifier = null)
{
if (is_int($char)) {
$charCode = $char;
$char = chr($charCode);
} else {
$charCode = ord($char);
}
$options = array(
'key' => $char,
'which' => $charCode,
'charCode' => $charCode,
'keyCode' => $charCode,
);
if ($modifier) {
$options[$modifier . 'Key'] = true;
}
$json = json_encode($options);
if ($json === false) {
throw new DriverException('Failed to encode options: ' . json_last_error_msg());
}
return $json;
}
/**
* Executes JS on a given element - pass in a js script string and {{ELEMENT}} will
* be replaced with a reference to the result of the $xpath query
*
* @example $this->executeJsOnXpath($xpath, 'return {{ELEMENT}}.childNodes.length');
*
* @param string $xpath the xpath to search with
* @param string $script the script to execute
* @param bool $sync whether to run the script synchronously (default is TRUE)
*
* @return mixed
*
* @throws DriverException
*/
protected function executeJsOnXpath(string $xpath, string $script, bool $sync = true)
{
return $this->executeJsOnElement($this->findElement($xpath), $script, $sync);
}
/**
* Executes JS on a given element - pass in a js script string and {{ELEMENT}} will
* be replaced with a reference to the element
*
* @example $this->executeJsOnXpath($xpath, 'return {{ELEMENT}}.childNodes.length');
*
* @param Element $element the webdriver element
* @param string $script the script to execute
* @param bool $sync whether to run the script synchronously (default is TRUE)
*
* @return mixed
*/
private function executeJsOnElement(Element $element, string $script, bool $sync = true)
{
$script = str_replace('{{ELEMENT}}', 'arguments[0]', $script);
$options = array(
'script' => $script,
'args' => array($element),
);
if ($sync) {
return $this->getWebDriverSession()->execute($options);
}
return $this->getWebDriverSession()->execute_async($options);
}
public function start()
{
try {
$status = $this->webDriver->status();
$seleniumVersion = $status['build']['version'] ?? $status['nodes'][0]['version'] ?? 'unknown';
$seleniumMajorVersion = (int) explode('.', $seleniumVersion)[0];
} catch (\Throwable $ex) {
throw new DriverException("Selenium Server version could not be detected: {$ex->getMessage()}", 0, $ex);
}
if ($seleniumMajorVersion > 3) {
throw new DriverException(<<<TEXT
This driver requires Selenium version 3 or lower, but version {$seleniumVersion} was found.
Please use the "mink/webdriver-classic-driver" Mink driver or switch to Selenium Server 2.x/3.x.
TEXT
);
}
try {
$this->isW3C = $seleniumMajorVersion === 3;
$this->wdSession = $this->webDriver->session($this->browserName, $this->desiredCapabilities);
$this->applyTimeouts();
$this->initialWindowHandle = $this->getWebDriverSession()->window_handle();
} catch (\Exception $e) {
throw new DriverException('Could not open connection: ' . $e->getMessage(), 0, $e);
}
$this->started = true;
}
/**
* Sets the timeouts to apply to the webdriver session
*
* @param array{script?: int, implicit?: int, page?: int} $timeouts times are in milliseconds
*
* @return void
*
* @throws DriverException
*/
public function setTimeouts(array $timeouts)
{
$this->timeouts = $timeouts;
if ($this->isStarted()) {
$this->applyTimeouts();
}
}
/**
* Applies timeouts to the current session
*/
private function applyTimeouts(): void
{
$validTimeoutTypes = array('script', 'implicit', 'page', 'page load', 'pageLoad');
try {
foreach ($this->timeouts as $type => $param) {
if (!in_array($type, $validTimeoutTypes)) {
throw new DriverException('Invalid timeout type: ' . $type);
}
if ($type === 'page load' || $type === 'pageLoad') {
@trigger_error(
'Using "' . $type . '" timeout type is deprecated, please use "page" instead',
E_USER_DEPRECATED
);
$type = 'page';
}
if ($type === 'page') {
$type = $this->isW3C ? 'pageLoad' : 'page load';
}
if ($this->isW3C) {
$this->getWebDriverSession()->timeouts(array($type => $param));
} else {
$this->getWebDriverSession()->timeouts($type, $param);
}
}
} catch (UnknownError|InvalidArgument $e) {
// UnknownError (Selenium 2.x). InvalidArgument (Selenium 3.x).
throw new DriverException('Error setting timeout: ' . $e->getMessage(), 0, $e);
}
}
public function isStarted()
{
return $this->started;
}
public function stop()
{
if (!$this->wdSession) {
throw new DriverException('Could not connect to a Selenium 2 / WebDriver server');
}
$this->started = false;
$this->isW3C = false;
try {
$this->wdSession->close();
} catch (\Exception $e) {
throw new DriverException('Could not close connection', 0, $e);
}
}
public function reset()
{
$webDriverSession = $this->getWebDriverSession();
// Close all windows except the initial one.
foreach ($webDriverSession->window_handles() as $windowHandle) {
if ($windowHandle === $this->initialWindowHandle) {
continue;
}
$webDriverSession->focusWindow($windowHandle);
$webDriverSession->deleteWindow();
}
$this->switchToWindow();
$webDriverSession->deleteAllCookies();
}
public function visit(string $url)
{
try {
$this->getWebDriverSession()->open($url);
} catch (ScriptTimeout|Timeout $e) {
// ScriptTimeout (Selenium 2.x). Timeout (Selenium 3.x).
throw new DriverException('Page failed to load: ' . $e->getMessage(), 0, $e);
}
}
public function getCurrentUrl()
{
return $this->getWebDriverSession()->url();
}
public function reload()
{
$this->getWebDriverSession()->refresh();
}
public function forward()
{
$this->getWebDriverSession()->forward();
}
public function back()
{
$this->getWebDriverSession()->back();
}
public function switchToWindow(?string $name = null)
{
$handle = $name === null
? $this->initialWindowHandle
: $this->getWindowHandleFromName($name);
$this->getWebDriverSession()->focusWindow($handle);
}
/**
* @throws DriverException
*/
private function getWindowHandleFromName(string $name): string
{
// if name is actually prefixed window handle, just remove the prefix
if (strpos($name, self::W3C_WINDOW_HANDLE_PREFIX) === 0) {
return substr($name, strlen(self::W3C_WINDOW_HANDLE_PREFIX));
}
// ..otherwise check if any existing window has the specified name
$origWindowHandle = $this->getWebDriverSession()->window_handle();
try {
foreach ($this->getWebDriverSession()->window_handles() as $handle) {
$this->getWebDriverSession()->focusWindow($handle);
if ($this->evaluateScript('window.name') === $name) {
return $handle;
}
}
throw new DriverException("Could not find handle of window named \"$name\"");
} finally {
$this->getWebDriverSession()->focusWindow($origWindowHandle);
}
}
public function switchToIFrame(?string $name = null)
{
$frameQuery = $name;
if ($name) {
try {
$frameQuery = $this->getWebDriverSession()->element('id', $name);
} catch (NoSuchElement $e) {
$frameQuery = $this->getWebDriverSession()->element('name', $name);
}
$frameQuery = $this->serializeWebElement($frameQuery);
}
$this->getWebDriverSession()->frame(array('id' => $frameQuery));
}
/**
* Serialize an Web Element
*
* @param Element $webElement Web webElement.
*
* @return array
* @todo Remove once the https://github.com/instaclick/php-webdriver/issues/131 is fixed.
*/
private function serializeWebElement(Element $webElement)
{
// Code for WebDriver 2.x version.
if (class_exists('\WebDriver\LegacyElement') && \defined('\WebDriver\Element::WEB_ELEMENT_ID')) {
if ($webElement instanceof \WebDriver\LegacyElement) {
return array(\WebDriver\LegacyElement::LEGACY_ELEMENT_ID => $webElement->getID());
}
return array(Element::WEB_ELEMENT_ID => $webElement->getID());
}
// Code for WebDriver 1.x version.
return array(
\WebDriver\Container::WEBDRIVER_ELEMENT_ID => $webElement->getID(),
\WebDriver\Container::LEGACY_ELEMENT_ID => $webElement->getID(),
);
}
public function setCookie(string $name, ?string $value = null)
{
if (null === $value) {
$this->getWebDriverSession()->deleteCookie($name);
return;
}
// PHP 7.4 changed the way it encodes cookies to better respect the spec.
// This assumes that the server and the Mink client run on the same version (or
// at least the same side of the behavior change), so that the server and Mink
// consider the same value.
if (\PHP_VERSION_ID >= 70400) {
$encodedValue = rawurlencode($value);
} else {
$encodedValue = urlencode($value);
}
$cookieArray = array(
'name' => $name,
'value' => $encodedValue,
'secure' => false, // thanks, chibimagic!
);
$this->getWebDriverSession()->setCookie($cookieArray);
}
public function getCookie(string $name)
{
$cookies = $this->getWebDriverSession()->getAllCookies();
foreach ($cookies as $cookie) {
if ($cookie['name'] === $name) {
// PHP 7.4 changed the way it encodes cookies to better respect the spec.
// This assumes that the server and the Mink client run on the same version (or
// at least the same side of the behavior change), so that the server and Mink
// consider the same value.
if (\PHP_VERSION_ID >= 70400) {
return rawurldecode($cookie['value']);
}
return urldecode($cookie['value']);
}
}
return null;
}
public function getContent()
{
return $this->getWebDriverSession()->source();
}
public function getScreenshot()
{
return base64_decode($this->getWebDriverSession()->screenshot());
}
public function getWindowNames()
{
$origWindow = $this->getWebDriverSession()->window_handle();
try {
$result = array();
foreach ($this->getWebDriverSession()->window_handles() as $tempWindow) {
$this->getWebDriverSession()->focusWindow($tempWindow);
$result[] = $this->getWindowName();
}
return $result;
} finally {
$this->getWebDriverSession()->focusWindow($origWindow);
}
}
public function getWindowName()
{
$name = (string) $this->evaluateScript('window.name');
if ($name === '') {
$name = self::W3C_WINDOW_HANDLE_PREFIX . $this->getWebDriverSession()->window_handle();
}
return $name;
}
/**
* @protected
*/
public function findElementXpaths(string $xpath)
{
$nodes = $this->getWebDriverSession()->elements('xpath', $xpath);
$elements = array();
foreach ($nodes as $i => $node) {
$elements[] = sprintf('(%s)[%d]', $xpath, $i+1);
}
return $elements;
}
public function getTagName(string $xpath)
{
return $this->findElement($xpath)->name();
}
public function getText(string $xpath)
{
return trim(str_replace(
array("\r\n", "\r", "\n", "\xc2\xa0"),
' ',
$this->executeJsOnXpath($xpath, 'return {{ELEMENT}}.innerText;')
));
}
public function getHtml(string $xpath)
{
return $this->executeJsOnXpath($xpath, 'return {{ELEMENT}}.innerHTML;');
}
public function getOuterHtml(string $xpath)
{
return $this->executeJsOnXpath($xpath, 'return {{ELEMENT}}.outerHTML;');
}
public function getAttribute(string $xpath, string $name)
{
$script = 'return {{ELEMENT}}.getAttribute(' . json_encode((string) $name) . ')';
return $this->executeJsOnXpath($xpath, $script);
}
public function getValue(string $xpath)
{
$element = $this->findElement($xpath);
$elementName = strtolower($element->name());
$elementType = strtolower($element->attribute('type') ?: '');
// Getting the value of a checkbox returns its value if selected.
if ('input' === $elementName && 'checkbox' === $elementType) {
return $element->selected() ? $element->attribute('value') : null;
}
if ('input' === $elementName && 'radio' === $elementType) {
$script = <<<JS
var node = {{ELEMENT}},
value = null;
var name = node.getAttribute('name');
if (name) {
var fields = window.document.getElementsByName(name),
i, l = fields.length;
for (i = 0; i < l; i++) {
var field = fields.item(i);
if (field.form === node.form && field.checked) {
value = field.value;
break;
}
}
}
return value;
JS;
return $this->executeJsOnElement($element, $script);
}
// Using $element->attribute('value') on a select only returns the first selected option
// even when it is a multiple select, so a custom retrieval is needed.
if ('select' === $elementName && $element->attribute('multiple')) {
$script = <<<JS
var node = {{ELEMENT}},
value = [];
for (var i = 0; i < node.options.length; i++) {
if (node.options[i].selected) {
value.push(node.options[i].value);
}
}
return value;
JS;
return $this->executeJsOnElement($element, $script);
}
return $element->attribute('value');
}
public function setValue(string $xpath, $value)
{
$element = $this->findElement($xpath);
$elementName = strtolower($element->name());
if ('select' === $elementName) {
if (is_array($value)) {
$this->deselectAllOptions($element);
foreach ($value as $option) {
$this->selectOptionOnElement($element, $option, true);
}
return;
}
if (\is_bool($value)) {
throw new DriverException('Boolean values cannot be used for a select element.');
}
$this->selectOptionOnElement($element, $value);
return;
}
if ('input' === $elementName) {
$elementType = strtolower($element->attribute('type') ?: '');
if (in_array($elementType, array('submit', 'image', 'button', 'reset'))) {
throw new DriverException(sprintf('Impossible to set value an element with XPath "%s" as it is not a select, textarea or textbox', $xpath));
}
if ('checkbox' === $elementType) {
if (!is_bool($value)) {
throw new DriverException('Only boolean values can be used for a checkbox input.');
}
if ($element->selected() xor $value) {
$this->clickOnElement($element);
}
return;
}
if ('radio' === $elementType) {
if (!\is_string($value)) {
throw new DriverException('Only string values can be used for a radio input.');
}
$this->selectRadioValue($element, $value);
return;
}
if ('file' === $elementType) {
if (!\is_string($value)) {
throw new DriverException('Only string values can be used for a file input.');
}
$element->postValue(array('value' => array(strval($value))));
return;
}
}
if (!\is_string($value)) {
throw new DriverException(sprintf('Only string values can be used for a %s element.', $elementName));
}
$value = strval($value);
if (in_array($elementName, array('input', 'textarea'))) {
$existingValueLength = strlen($element->attribute('value'));
$value = str_repeat(Key::BACKSPACE . Key::DELETE, $existingValueLength) . $value;
}
$element->postValue(array('value' => array($value)));
// Remove the focus from the element if the field still has focus in
// order to trigger the change event. By doing this instead of simply
// triggering the change event for the given xpath we ensure that the
// change event will not be triggered twice for the same element if it
// has lost focus in the meanwhile. If the element has lost focus
// already then there is nothing to do as this will already have caused
// the triggering of the change event for that element.
$script = <<<JS
var node = {{ELEMENT}};
if (document.activeElement === node) {
document.activeElement.blur();
}
JS;
// Cover case, when an element was removed from DOM after its value was
// changed (e.g. by a JavaScript of a SPA) and therefore can't be focused.
try {
$this->executeJsOnElement($element, $script);
} catch (StaleElementReference $e) {
// Do nothing because an element was already removed and therefore
// blurring is not needed.
}
}
public function check(string $xpath)
{
$element = $this->findElement($xpath);
$this->ensureInputType($element, $xpath, 'checkbox', 'check');
if ($element->selected()) {
return;
}
$this->clickOnElement($element);
}
public function uncheck(string $xpath)
{
$element = $this->findElement($xpath);
$this->ensureInputType($element, $xpath, 'checkbox', 'uncheck');
if (!$element->selected()) {
return;
}
$this->clickOnElement($element);
}
public function isChecked(string $xpath)
{
return $this->findElement($xpath)->selected();
}
public function selectOption(string $xpath, string $value, bool $multiple = false)
{
$element = $this->findElement($xpath);
$tagName = strtolower($element->name());
if ('input' === $tagName && 'radio' === strtolower($element->attribute('type') ?: '')) {
$this->selectRadioValue($element, $value);
return;
}
if ('select' === $tagName) {
$this->selectOptionOnElement($element, $value, $multiple);
return;
}
throw new DriverException(sprintf('Impossible to select an option on the element with XPath "%s" as it is not a select or radio input', $xpath));
}
public function isSelected(string $xpath)
{
return $this->findElement($xpath)->selected();
}
public function click(string $xpath)
{
$this->clickOnElement($this->findElement($xpath));
}
private function clickOnElement(Element $element): void
{
try {
// Move the mouse to the element as Selenium does not allow clicking on an element which is outside the viewport
$this->getWebDriverSession()->moveto(array('element' => $element->getID()));
} catch (UnknownCommand $e) {
// If the Webdriver implementation does not support moveto (which is not part of the W3C WebDriver spec), proceed to the click
} catch (UnknownError $e) {
// Chromium driver sends back UnknownError (WebDriver\Exception with code 13)
}
$element->click();
}
public function doubleClick(string $xpath)
{
$this->mouseOver($xpath);
$this->getWebDriverSession()->doubleclick();
}
public function rightClick(string $xpath)
{
if ($this->isW3C) {
// See: https://github.com/SeleniumHQ/selenium/commit/085ceed1f55fbaaa1d419b19c73264415c394905.
throw new DriverException(<<<TEXT
Right-clicking via JsonWireProtocol is not possible on Selenium Server 3.x.
Please use the "mink/webdriver-classic-driver" Mink driver or switch to Selenium Server 2.x.
TEXT
);
}
$this->mouseOver($xpath);
$this->getWebDriverSession()->click(array('button' => 2));
}
public function attachFile(string $xpath, string $path)
{
$element = $this->findElement($xpath);
$this->ensureInputType($element, $xpath, 'file', 'attach a file on');
// Upload the file to Selenium and use the remote path. This will
// ensure that Selenium always has access to the file, even if it runs
// as a remote instance.
try {
$remotePath = $this->uploadFile($path);
} catch (\Exception $e) {
// File could not be uploaded to remote instance. Use the local path.
$remotePath = $path;
}
$element->postValue(array('value' => array($remotePath)));
}
public function isVisible(string $xpath)
{
return $this->findElement($xpath)->displayed();
}
public function mouseOver(string $xpath)
{
$this->getWebDriverSession()->moveto(array(
'element' => $this->findElement($xpath)->getID()
));
}
public function focus(string $xpath)
{
$this->trigger($xpath, 'focus');