Passed
Push — master ( 9377d0...328d63 )
by Robert
04:55 queued 02:12
created

PantherDriver::attachFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 11
ccs 0
cts 6
cp 0
crap 6
rs 10
1
<?php
2
declare(strict_types=1);
3
4
/*
5
 * This file is part of the Behat\Mink.
6
 * (c) Robert Freigang <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Behat\Mink\Driver;
13
14
use Behat\Mink\Exception\DriverException;
15
use Behat\Mink\Exception\UnsupportedDriverActionException;
16
use Facebook\WebDriver\Interactions\Internal\WebDriverCoordinates;
17
use Facebook\WebDriver\Interactions\WebDriverActions;
18
use Facebook\WebDriver\Internal\WebDriverLocatable;
19
use Facebook\WebDriver\JavaScriptExecutor;
20
use Facebook\WebDriver\WebDriverDimension;
21
use Facebook\WebDriver\WebDriverElement;
22
use Facebook\WebDriver\WebDriverHasInputDevices;
23
use Facebook\WebDriver\WebDriverKeys;
24
use Symfony\Component\BrowserKit\Cookie;
25
use Symfony\Component\BrowserKit\Response;
26
use Symfony\Component\DomCrawler\Field\FormField;
27
use Symfony\Component\Panther\Client;
28
use Symfony\Component\Panther\DomCrawler\Crawler;
29
use Symfony\Component\Panther\DomCrawler\Field\ChoiceFormField;
30
use Symfony\Component\Panther\DomCrawler\Field\FileFormField;
31
use Symfony\Component\Panther\DomCrawler\Field\InputFormField;
32
use Symfony\Component\Panther\DomCrawler\Field\TextareaFormField;
33
use Symfony\Component\Panther\PantherTestCaseTrait;
34
35
/**
36
 * Symfony2 Panther driver.
37
 *
38
 * @author Robert Freigang <[email protected]>
39
 */
40
class PantherDriver extends CoreDriver
41
{
42
    use PantherTestCaseTrait;
43
44
    // PantherTestCaseTrait needs this constants; provided via "\Symfony\Component\Panther\PantherTestCase"
45
    public const CHROME = 'chrome';
46
    public const FIREFOX = 'firefox';    
47
    
48
    /** @var Client */
49
    private $client;
50
    private $started = false;
51
    private $removeScriptFromUrl = false;
52
    private $removeHostFromUrl = false;
53
    /** @var array */
54
    private $options;
55
56 10
    public function __construct(
57
        array $options = []
58
    ) {
59 10
        $this->options = $options;
60 10
    }
61
62
    /**
63
     * Returns BrowserKit HTTP client instance.
64
     *
65
     * @return Client
66
     */
67
    public function getClient()
68
    {
69
        return $this->client;
70
    }
71
72
    /**
73
     * Tells driver to remove hostname from URL.
74
     *
75
     * @param Boolean $remove
76
     *
77
     * @deprecated Deprecated as of 1.2, to be removed in 2.0. Pass the base url in the constructor instead.
78
     */
79
    public function setRemoveHostFromUrl($remove = true)
80
    {
81
        @trigger_error(
82
            'setRemoveHostFromUrl() is deprecated as of 1.2 and will be removed in 2.0. Pass the base url in the constructor instead.',
83
            E_USER_DEPRECATED
84
        );
85
        $this->removeHostFromUrl = (bool)$remove;
86
    }
87
88
    /**
89
     * Tells driver to remove script name from URL.
90
     *
91
     * @param Boolean $remove
92
     *
93
     * @deprecated Deprecated as of 1.2, to be removed in 2.0. Pass the base url in the constructor instead.
94
     */
95
    public function setRemoveScriptFromUrl($remove = true)
96
    {
97
        @trigger_error(
98
            'setRemoveScriptFromUrl() is deprecated as of 1.2 and will be removed in 2.0. Pass the base url in the constructor instead.',
99
            E_USER_DEPRECATED
100
        );
101
        $this->removeScriptFromUrl = (bool)$remove;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function start()
108
    {
109
        $this->client = self::createPantherClient($this->options);
110
        $this->client->start();
111
112
        $this->started = true;
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118 10
    public function isStarted()
119
    {
120 10
        return $this->started;
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function stop()
127
    {
128
        $this->client->quit();
129
        self::stopWebServer();
130
        $this->started = false;
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136
    public function reset()
137
    {
138
        // experimental
139
        // $useSpeedUp = false;
140
        $useSpeedUp = true;
141
        if ($useSpeedUp) {
0 ignored issues
show
introduced by
The condition $useSpeedUp is always true.
Loading history...
142
            $this->client->getWebDriver()->manage()->deleteAllCookies();
143
            $history = $this->client->getHistory();
144
            if ($history) {
0 ignored issues
show
introduced by
$history is of type Symfony\Component\BrowserKit\History, thus it always evaluated to true.
Loading history...
145
                $history->clear();
146
            }
147
            if (
148
                $this->client->getWebDriver() instanceof JavaScriptExecutor
149
                && !in_array($this->client->getCurrentURL(), ['', 'about:blank', 'data:,'], true)
150
            ) {
151
                $this->executeScript('localStorage.clear();');
152
            }
153
            // not sure if we should also close all windows
154
            // $lastWindowHandle = \end($this->client->getWindowHandles());
155
            // if ($lastWindowHandle) {
156
            //     $this->client->switchTo()->window($lastWindowHandle);
157
            // }
158
            // $this->client->getWebDriver()->navigate()->refresh();
159
            // $this->client->refreshCrawler();
160
            // if (\count($this->client->getWindowHandles()) > 1) {
161
            //     $this->client->getWebDriver()->close();
162
            // }
163
        } else {
164
            // Restarting the client resets the cookies and the history
165
            $this->client->restart();
166
        }
167
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173
    public function visit($url)
174
    {
175
        $this->client->get($this->prepareUrl($url));
176
    }
177
178
    /**
179
     * {@inheritdoc}
180
     */
181
    public function getCurrentUrl()
182
    {
183
        return $this->client->getCurrentURL();
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189
    public function reload()
190
    {
191
        $this->client->reload();
192
    }
193
194
    /**
195
     * {@inheritdoc}
196
     */
197
    public function forward()
198
    {
199
        $this->client->forward();
200
    }
201
202
    /**
203
     * {@inheritdoc}
204
     */
205
    public function back()
206
    {
207
        $this->client->back();
208
    }
209
210
    /**
211
     * {@inheritdoc}
212
     */
213
    public function switchToWindow($name = null)
214
    {
215
        $this->client->switchTo()->window($name);
216
        $this->client->refreshCrawler();
217
    }
218
219
    /**
220
     * {@inheritdoc}
221
     */
222
    public function switchToIFrame($name = null)
223
    {
224
        if (null === $name) {
225
            $this->client->switchTo()->defaultContent();
226
        } elseif ($name) {
227
            $iFrameElement = $this->getCrawlerElement($this->getFilteredCrawler(\sprintf("//iframe[@name='%s']", $name)));
228
            $this->client->switchTo()->frame($iFrameElement);
229
        } else {
230
            $this->client->switchTo()->frame(null);
231
        }
232
        $this->client->refreshCrawler();
233
    }
234
235
    /**
236
     * {@inheritdoc}
237
     */
238
    public function setCookie($name, $value = null)
239
    {
240
        if (null === $value) {
241
            $this->deleteCookie($name);
242
243
            return;
244
        }
245
246
        $jar = $this->client->getCookieJar();
247
        // @see: https://github.com/w3c/webdriver/issues/1238
248
        $jar->set(new Cookie($name, \rawurlencode((string)$value)));
249
    }
250
251
    /**
252
     * Deletes a cookie by name.
253
     *
254
     * @param string $name Cookie name.
255
     */
256
    private function deleteCookie($name)
257
    {
258
        $path = $this->getCookiePath();
259
        $jar = $this->client->getCookieJar();
260
261
        do {
262
            if (null !== $jar->get($name, $path)) {
263
                $jar->expire($name, $path);
264
            }
265
266
            $path = preg_replace('/.$/', '', $path);
267
        } while ($path);
268
    }
269
270
    /**
271
     * Returns current cookie path.
272
     *
273
     * @return string
274
     */
275
    private function getCookiePath()
276
    {
277
        $path = dirname(parse_url($this->getCurrentUrl(), PHP_URL_PATH));
278
279
        if ('\\' === DIRECTORY_SEPARATOR) {
280
            $path = str_replace('\\', '/', $path);
281
        }
282
283
        return $path;
284
    }
285
286
    /**
287
     * {@inheritdoc}
288
     */
289
    public function getCookie($name)
290
    {
291
        $cookies = $this->client->getCookieJar()->all();
292
293
        foreach ($cookies as $cookie) {
294
            if ($cookie->getName() === $name) {
295
                return \urldecode($cookie->getValue());
296
            }
297
        }
298
299
        return null;
300
    }
301
302
    /**
303
     * {@inheritdoc}
304
     */
305
    public function getContent()
306
    {
307
        return $this->client->getWebDriver()->getPageSource();
308
    }
309
310
    /**
311
     * {@inheritdoc}
312
     */
313
    public function getScreenshot($saveAs = null): string
314
    {
315
        return $this->client->takeScreenshot($saveAs);
316
    }
317
318
    /**
319
     * {@inheritdoc}
320
     */
321
    public function getWindowNames()
322
    {
323
        return $this->client->getWindowHandles();
324
    }
325
326
    /**
327
     * {@inheritdoc}
328
     */
329
    public function getWindowName()
330
    {
331
        return $this->client->getWindowHandle();
332
    }
333
334
    /**
335
     * {@inheritdoc}
336
     */
337
    public function isVisible($xpath)
338
    {
339
        return $this->getCrawlerElement($this->getFilteredCrawler($xpath))->isDisplayed();
340
    }
341
342
    /**
343
     * {@inheritdoc}.
344
     */
345
    public function mouseOver($xpath)
346
    {
347
        $this->client->getMouse()->mouseMove($this->toCoordinates($xpath));
348
    }
349
350
    /**
351
     * {@inheritdoc}
352
     */
353
    public function focus($xpath)
354
    {
355
        $jsNode = $this->getJsNode($xpath);
356
        $script = \sprintf('%s.focus()', $jsNode);
357
        $this->executeScript($script);
358
    }
359
360
    /**
361
     * {@inheritdoc}
362
     */
363
    public function blur($xpath)
364
    {
365
        $jsNode = $this->getJsNode($xpath);
366
        $script = \sprintf('%s.blur();', $jsNode);
367
        // ensure element had active state; just for passing EventsTest::testBlur
368
        if ($this->evaluateScript(\sprintf('document.activeElement !== %s', $jsNode))) {
369
            $script = \sprintf('%s.focus();%s', $jsNode, $script);
370
        }
371
        $this->executeScript($script);
372
    }
373
374
    /**
375
     * {@inheritdoc}
376
     */
377
    public function keyPress($xpath, $char, $modifier = null)
378
    {
379
        $webDriverActions = $this->getWebDriverActions();
380
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
381
        $key = $this->geWebDriverKeyValue($char);
382
383
        $modifier = $this->getWebdriverModifierKeyValue($modifier);
384
385
        if ($modifier) {
386
            $webDriverActions->keyDown($element, $modifier)->perform();
387
            $webDriverActions->sendKeys($element, $key)->perform();
388
            $webDriverActions->keyUp($element, $modifier)->perform();
389
        } else {
390
            $webDriverActions->sendKeys($element, $key)->perform();
391
        }
392
    }
393
394
    /**
395
     * {@inheritdoc}
396
     */
397
    public function keyDown($xpath, $char, $modifier = null)
398
    {
399
        $webDriverActions = $this->getWebDriverActions();
400
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
401
        $key = $this->geWebDriverKeyValue($char);
402
403
        $webDriverActions->keyDown($element, $key)->perform();
404
        $modifier = $this->getWebdriverModifierKeyValue($modifier);
405
        if ($modifier) {
406
            $webDriverActions->keyDown($element, $modifier)->perform();
407
        }
408
    }
409
410
    /**
411
     * {@inheritdoc}
412
     */
413
    public function keyUp($xpath, $char, $modifier = null)
414
    {
415
        $webDriverActions = $this->getWebDriverActions();
416
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
417
        $key = $this->geWebDriverKeyValue($char);
418
419
        $modifier = $this->getWebdriverModifierKeyValue($modifier);
420
        if ($modifier) {
421
            $webDriverActions->keyDown($element, $modifier)->perform();
422
        }
423
424
        $webDriverActions->keyDown($element, $key)->perform();
425
        $webDriverActions->keyUp($element, $key)->perform();
426
        if ($modifier) {
427
            $webDriverActions->keyUp($element, $modifier)->perform();
428
        }
429
    }
430
431
    /**
432
     * {@inheritdoc}
433
     */
434
    public function isSelected($xpath)
435
    {
436
        return $this->getCrawlerElement($this->getFilteredCrawler($xpath))->isSelected();
437
    }
438
439
    /**
440
     * {@inheritdoc}
441
     */
442
    public function findElementXpaths($xpath)
443
    {
444
        $nodes = $this->getCrawler()->filterXPath($xpath);
445
446
        $elements = array();
447
        foreach ($nodes as $i => $node) {
448
            $elements[] = sprintf('(%s)[%d]', $xpath, $i + 1);
449
        }
450
451
        return $elements;
452
    }
453
454
    /**
455
     * {@inheritdoc}
456
     */
457
    public function getTagName($xpath)
458
    {
459
        return $this->getCrawlerElement($this->getFilteredCrawler($xpath))->getTagName();
460
    }
461
462
    /**
463
     * {@inheritdoc}
464
     */
465
    public function getText($xpath)
466
    {
467
        $text = $this->getFilteredCrawler($xpath)->text();
468
        $text = str_replace("\n", ' ', $text);
469
        $text = preg_replace('/ {2,}/', ' ', $text);
470
471
        return trim($text);
472
    }
473
474
    /**
475
     * {@inheritdoc}
476
     */
477
    public function getHtml($xpath)
478
    {
479
        // cut the tag itself (making innerHTML out of outerHTML)
480
        return preg_replace('/^\<[^\>]+\>|\<[^\>]+\>$/', '', $this->getOuterHtml($xpath));
481
    }
482
483
    /**
484
     * {@inheritdoc}
485
     */
486
    public function getOuterHtml($xpath)
487
    {
488
        $crawler = $this->getFilteredCrawler($xpath);
489
490
        return $crawler->html();
491
    }
492
493
    /**
494
     * {@inheritdoc}
495
     */
496
    public function getAttribute($xpath, $name)
497
    {
498
        $crawler = $this->getFilteredCrawler($xpath);
499
500
        $attribute = $this->getCrawlerElement($crawler)->getAttribute($name);
501
502
        // let's get hacky
503
        if ('' === $attribute) {
504
            $html = \strtolower($crawler->html());
505
            $name = \strtolower($name).'=';
506
            if (0 === \substr_count($html, $name)) {
507
                $attribute = null;
508
            }
509
        }
510
511
        return $attribute;
512
    }
513
514
    /**
515
     * {@inheritdoc}
516
     */
517
    public function getValue($xpath)
518
    {
519
        try {
520
            $formField = $this->getFormField($xpath);
521
            $value = $formField->getValue();
522
            if ('' === $value && $formField instanceof ChoiceFormField) {
523
                $value = null;
524
            }
525
        } catch (DriverException $e) {
526
            // e.g. element is an option
527
            $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
528
            $value = $element->getAttribute('value');
529
        }
530
531
         return $value;
532
    }
533
534
    /**
535
     * {@inheritdoc}
536
     */
537
    public function setValue($xpath, $value)
538
    {
539
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
540
        $jsNode = $this->getJsNode($xpath);
541
542
        if ('input' === $element->getTagName() && \in_array($element->getAttribute('type'), ['date', 'time', 'color'])) {
543
            $this->executeScript(\sprintf('%s.value = \'%s\'', $jsNode, $value));
544
        } else {
545
            try {
546
                $formField = $this->getFormField($xpath);
547
                $formField->setValue($value);
548
            } catch (DriverException $e) {
549
                // e.g. element is on option
550
                $element->sendKeys($value);
551
            }
552
        }
553
554
        // Remove the focus from the element if the field still has focus in
555
        // order to trigger the change event. By doing this instead of simply
556
        // triggering the change event for the given xpath we ensure that the
557
        // change event will not be triggered twice for the same element if it
558
        // has lost focus in the meanwhile. If the element has lost focus
559
        // already then there is nothing to do as this will already have caused
560
        // the triggering of the change event for that element.
561
        if ($this->evaluateScript(\sprintf('document.activeElement === %s', $jsNode))) {
562
            $this->executeScript('document.activeElement.blur();');
563
        }
564
    }
565
566
    /**
567
     * {@inheritdoc}
568
     */
569
    public function check($xpath)
570
    {
571
        $this->getChoiceFormField($xpath)->tick();
572
    }
573
574
    /**
575
     * {@inheritdoc}
576
     */
577
    public function uncheck($xpath)
578
    {
579
        $this->getChoiceFormField($xpath)->untick();
580
    }
581
582
    /**
583
     * {@inheritdoc}
584
     */
585
    public function selectOption($xpath, $value, $multiple = false)
586
    {
587
        $field = $this->getFormField($xpath);
588
589
        if (!$field instanceof ChoiceFormField) {
590
            throw new DriverException(
591
                sprintf('Impossible to select an option on the element with XPath "%s" as it is not a select or radio input', $xpath)
592
            );
593
        }
594
595
        $field->select($value);
596
    }
597
598
    /**
599
     * {@inheritdoc}
600
     */
601
    public function click($xpath)
602
    {
603
        $this->client->getMouse()->click($this->toCoordinates($xpath));
604
        $this->client->refreshCrawler();
605
    }
606
607
    /**
608
     * {@inheritdoc}
609
     */
610
    public function doubleClick($xpath)
611
    {
612
        $this->client->getMouse()->doubleClick($this->toCoordinates($xpath));
613
    }
614
615
    /**
616
     * {@inheritdoc}
617
     */
618
    public function rightClick($xpath)
619
    {
620
        $this->client->getMouse()->contextClick($this->toCoordinates($xpath));
621
    }
622
623
    /**
624
     * {@inheritdoc}
625
     */
626
    public function isChecked($xpath)
627
    {
628
        return $this->getChoiceFormField($xpath)->hasValue();
629
    }
630
631
    /**
632
     * {@inheritdoc}
633
     */
634
    public function attachFile($xpath, $path)
635
    {
636
        $field = $this->getFormField($xpath);
637
638
        if (!$field instanceof FileFormField) {
639
            throw new DriverException(
640
                sprintf('Impossible to attach a file on the element with XPath "%s" as it is not a file input', $xpath)
641
            );
642
        }
643
644
        $field->upload($path);
645
    }
646
647
    /**
648
     * {@inheritdoc}
649
     */
650
    public function dragTo($sourceXpath, $destinationXpath)
651
    {
652
        $webDriverActions = $this->getWebDriverActions();
653
        $source = $this->getCrawlerElement($this->getFilteredCrawler($sourceXpath));
654
        $target = $this->getCrawlerElement($this->getFilteredCrawler($destinationXpath));
655
        $webDriverActions->dragAndDrop($source, $target)->perform();
656
    }
657
658
    /**
659
     * {@inheritdoc}
660
     */
661
    public function executeScript($script)
662
    {
663
        if (\preg_match('/^function[\s\(]/', $script)) {
664
            $script = \preg_replace('/;$/', '', $script);
665
            $script = '(' . $script . ')';
666
        }
667
668
        return $this->client->executeScript($script);
669
    }
670
671
    /**
672
     * {@inheritdoc}
673
     */
674
    public function evaluateScript($script)
675
    {
676
        if (0 !== \strpos(\trim($script), 'return ')) {
677
            $script = 'return ' . $script;
678
        }
679
680
        return $this->client->executeScript($script);
681
    }
682
683
    /**
684
     * {@inheritdoc}
685
     */
686
    public function wait($timeout, $condition)
687
    {
688
        $script = "return $condition;";
689
        $start = microtime(true);
690
        $end = $start + $timeout / 1000.0;
691
692
        do {
693
            $result = $this->evaluateScript($script);
694
            \usleep(100000);
695
        } while (\microtime(true) < $end && !$result);
696
697
        return (bool) $result;
698
    }
699
700
    /**
701
     * {@inheritdoc}
702
     */
703
    public function resizeWindow($width, $height, $name = null)
704
    {
705
        $size = new WebDriverDimension($width, $height);
706
        $this->client->getWebDriver()->manage()->window()->setSize($size);
707
    }
708
709
    /**
710
     * {@inheritdoc}
711
     */
712
    public function maximizeWindow($name = null)
713
    {
714
        $width = $this->evaluateScript('screen.width');
715
        $height = $this->evaluateScript('screen.height');
716
        $this->resizeWindow($width, $height, $name);
717
    }
718
719
    /**
720
     * {@inheritdoc}
721
     */
722
    public function submitForm($xpath)
723
    {
724
        $crawler = $this->getFilteredCrawler($xpath);
725
726
        $this->client->submit($crawler->form());
727
        $this->client->refreshCrawler();
728
    }
729
730
    /**
731
     * @return Response
732
     *
733
     * @throws DriverException If there is not response yet
734
     */
735
    protected function getResponse()
736
    {
737
        $response = $this->client->getInternalResponse();
738
739
        if (null === $response) {
740
            throw new DriverException('Unable to access the response before visiting a page');
741
        }
742
743
        return $response;
744
    }
745
746
    /**
747
     * Prepares URL for visiting.
748
     * Removes "*.php/" from urls and then passes it to BrowserKitDriver::visit().
749
     *
750
     * @param string $url
751
     *
752
     * @return string
753
     */
754
    protected function prepareUrl($url)
755
    {
756
        $replacement = ($this->removeHostFromUrl ? '' : '$1').($this->removeScriptFromUrl ? '' : '$2');
757
758
        return preg_replace('#(https?\://[^/]+)(/[^/\.]+\.php)?#', $replacement, $url);
759
    }
760
761
    /**
762
     * Returns form field from XPath query.
763
     *
764
     * @param string $xpath
765
     *
766
     * @return FormField
767
     *
768
     * @throws DriverException
769
     */
770
    private function getFormField($xpath)
771
    {
772
        try {
773
            $formField = $this->getChoiceFormField($xpath);
774
        } catch (DriverException $e) {
775
            $formField = null;
776
        }
777
        if (!$formField) {
778
            try {
779
                $formField = $this->getInputFormField($xpath);
780
            } catch (DriverException $e) {
781
                $formField = null;
782
            }
783
        }
784
        if (!$formField) {
785
            try {
786
                $formField = $this->getFileFormField($xpath);
787
            } catch (DriverException $e) {
788
                $formField = null;
789
            }
790
        }
791
        if (!$formField) {
792
            $formField = $this->getTextareaFormField($xpath);
793
        }
794
795
        return $formField;
796
    }
797
798
    /**
799
     * Returns the checkbox field from xpath query, ensuring it is valid.
800
     *
801
     * @param string $xpath
802
     *
803
     * @return ChoiceFormField
804
     *
805
     * @throws DriverException when the field is not a checkbox
806
     */
807
    private function getChoiceFormField($xpath)
808
    {
809
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
810
        try {
811
            $choiceFormField = new ChoiceFormField($element);
812
        } catch (\LogicException $e) {
813
            throw new DriverException(
814
                sprintf(
815
                    'Impossible to get the element with XPath "%s" as it is not a choice form field. %s',
816
                    $xpath,
817
                    $e->getMessage()
818
                )
819
            );
820
        }
821
822
        return $choiceFormField;
823
    }
824
825
    /**
826
     * Returns the input field from xpath query, ensuring it is valid.
827
     *
828
     * @param string $xpath
829
     *
830
     * @return InputFormField
831
     *
832
     * @throws DriverException when the field is not a checkbox
833
     */
834
    private function getInputFormField($xpath)
835
    {
836
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
837
        try {
838
            $inputFormField = new InputFormField($element);
839
        } catch (\LogicException $e) {
840
            throw new DriverException(sprintf('Impossible to check the element with XPath "%s" as it is not an input form field.', $xpath));
841
        }
842
843
        return $inputFormField;
844
    }
845
846
    /**
847
     * Returns the input field from xpath query, ensuring it is valid.
848
     *
849
     * @param string $xpath
850
     *
851
     * @return FileFormField
852
     *
853
     * @throws DriverException when the field is not a checkbox
854
     */
855
    private function getFileFormField($xpath)
856
    {
857
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
858
        try {
859
            $fileFormField = new FileFormField($element);
860
        } catch (\LogicException $e) {
861
            throw new DriverException(sprintf('Impossible to check the element with XPath "%s" as it is not a file form field.', $xpath));
862
        }
863
864
        return $fileFormField;
865
    }
866
867
    /**
868
     * Returns the textarea field from xpath query, ensuring it is valid.
869
     *
870
     * @param string $xpath
871
     *
872
     * @return TextareaFormField
873
     *
874
     * @throws DriverException when the field is not a checkbox
875
     */
876
    private function getTextareaFormField($xpath)
877
    {
878
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
879
        try {
880
            $textareaFormField = new TextareaFormField($element);
881
        } catch (\LogicException $e) {
882
            throw new DriverException(sprintf('Impossible to check the element with XPath "%s" as it is not a textarea.', $xpath));
883
        }
884
885
        return $textareaFormField;
886
    }
887
888
    /**
889
     * Returns WebDriverElement from crawler instance.
890
     *
891
     * @param Crawler $crawler
892
     *
893
     * @return WebDriverElement
894
     *
895
     * @throws DriverException when the node does not exist
896
     */
897
    private function getCrawlerElement(Crawler $crawler): WebDriverElement
898
    {
899
        $node = $crawler->getElement(0);
900
901
        if (null !== $node) {
902
            return $node;
903
        }
904
905
        throw new DriverException('The element does not exist');
906
    }
907
908
    /**
909
     * Returns a crawler filtered for the given XPath, requiring at least 1 result.
910
     *
911
     * @param string $xpath
912
     *
913
     * @return Crawler
914
     *
915
     * @throws DriverException when no matching elements are found
916
     */
917
    private function getFilteredCrawler($xpath): Crawler
918
    {
919
        if (!count($crawler = $this->getCrawler()->filterXPath($xpath))) {
920
            throw new DriverException(sprintf('There is no element matching XPath "%s"', $xpath));
921
        }
922
923
        return $crawler;
924
    }
925
926
    /**
927
     * Returns crawler instance (got from client).
928
     *
929
     * @return Crawler
930
     *
931
     * @throws DriverException
932
     */
933
    private function getCrawler(): Crawler
934
    {
935
        $crawler = $this->client->getCrawler();
936
937
        if (null === $crawler) {
938
            throw new DriverException('Unable to access the response content before visiting a page');
939
        }
940
941
        return $crawler;
942
    }
943
944
    private function getJsNode(string $xpath): string
945
    {
946
        return sprintf('document.evaluate(`%s`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue', $xpath);
947
    }
948
949
    private function toCoordinates(string $xpath): WebDriverCoordinates
950
    {
951
        $element = $this->getCrawlerElement($this->getFilteredCrawler($xpath));
952
953
        if (!$element instanceof WebDriverLocatable) {
954
            throw new \RuntimeException(
955
                sprintf('The element of "%s" xpath selector does not implement "%s".', $xpath, WebDriverLocatable::class)
956
            );
957
        }
958
959
        return $element->getCoordinates();
960
    }
961
962
    private function getWebDriverActions(): WebDriverActions
963
    {
964
        $webDriver = $this->client->getWebDriver();
965
        if (!$webDriver instanceof WebDriverHasInputDevices) {
966
            throw new UnsupportedDriverActionException('Mouse manipulations are not supported by %s', $this);
967
        }
968
        $webDriverActions = new WebDriverActions($webDriver);
969
970
        return $webDriverActions;
971
    }
972
973
    private function geWebDriverKeyValue($char)
974
    {
975
        if (\is_int($char)) {
976
            $char = \strtolower(\chr($char));
977
        }
978
979
        return $char;
980
    }
981
982
    private function getWebdriverModifierKeyValue(string $modifier = null): ?string
983
    {
984
        switch ($modifier) {
985
            case 'alt':
986
                $modifier = WebDriverKeys::ALT;
987
                break;
988
            case 'ctrl':
989
                $modifier = WebDriverKeys::CONTROL;
990
                break;
991
            case 'shift':
992
                $modifier = WebDriverKeys::SHIFT;
993
                break;
994
            case 'meta':
995
                $modifier = WebDriverKeys::META;
996
                break;
997
            case null:
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $modifier of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
998
                break;
999
            default:
1000
                throw new DriverException(\sprintf('Unsupported modifier "%s" given.', $modifier));
1001
        }
1002
1003
        return $modifier;
1004
    }
1005
}
1006