Passed
Push — master ( 2843e3...0afa7e )
by Robert
03:29
created

PantherDriver::setValue()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.1502

Importance

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