1<?php
2
3namespace Facebook\WebDriver\Remote;
4
5use Facebook\WebDriver\WebDriver;
6use Facebook\WebDriver\WebDriverKeyboard;
7use Facebook\WebDriver\WebDriverKeys;
8
9/**
10 * Execute keyboard commands for RemoteWebDriver.
11 */
12class RemoteKeyboard implements WebDriverKeyboard
13{
14    /** @var RemoteExecuteMethod */
15    private $executor;
16    /** @var WebDriver */
17    private $driver;
18    /** @var bool */
19    private $isW3cCompliant;
20
21    /**
22     * @param bool $isW3cCompliant
23     */
24    public function __construct(RemoteExecuteMethod $executor, WebDriver $driver, $isW3cCompliant = false)
25    {
26        $this->executor = $executor;
27        $this->driver = $driver;
28        $this->isW3cCompliant = $isW3cCompliant;
29    }
30
31    /**
32     * Send keys to active element
33     * @param string|array $keys
34     * @return $this
35     */
36    public function sendKeys($keys)
37    {
38        if ($this->isW3cCompliant) {
39            $activeElement = $this->driver->switchTo()->activeElement();
40            $activeElement->sendKeys($keys);
41        } else {
42            $this->executor->execute(DriverCommand::SEND_KEYS_TO_ACTIVE_ELEMENT, [
43                'value' => WebDriverKeys::encode($keys),
44            ]);
45        }
46
47        return $this;
48    }
49
50    /**
51     * Press a modifier key
52     *
53     * @see WebDriverKeys
54     * @param string $key
55     * @return $this
56     */
57    public function pressKey($key)
58    {
59        if ($this->isW3cCompliant) {
60            $this->executor->execute(DriverCommand::ACTIONS, [
61                'actions' => [
62                    [
63                        'type' => 'key',
64                        'id' => 'keyboard',
65                        'actions' => [['type' => 'keyDown', 'value' => $key]],
66                    ],
67                ],
68            ]);
69        } else {
70            $this->executor->execute(DriverCommand::SEND_KEYS_TO_ACTIVE_ELEMENT, [
71                'value' => [(string) $key],
72            ]);
73        }
74
75        return $this;
76    }
77
78    /**
79     * Release a modifier key
80     *
81     * @see WebDriverKeys
82     * @param string $key
83     * @return $this
84     */
85    public function releaseKey($key)
86    {
87        if ($this->isW3cCompliant) {
88            $this->executor->execute(DriverCommand::ACTIONS, [
89                'actions' => [
90                    [
91                        'type' => 'key',
92                        'id' => 'keyboard',
93                        'actions' => [['type' => 'keyUp', 'value' => $key]],
94                    ],
95                ],
96            ]);
97        } else {
98            $this->executor->execute(DriverCommand::SEND_KEYS_TO_ACTIVE_ELEMENT, [
99                'value' => [(string) $key],
100            ]);
101        }
102
103        return $this;
104    }
105}
106