AbstractWebDriver.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. <?php
  2. /**
  3. * Copyright 2004-2017 Facebook. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. * @package WebDriver
  18. *
  19. * @author Justin Bishop <jubishop@gmail.com>
  20. * @author Anthon Pang <apang@softwaredevelopment.ca>
  21. * @author Fabrizio Branca <mail@fabrizio-branca.de>
  22. * @author Tsz Ming Wong <tszming@gmail.com>
  23. */
  24. namespace WebDriver;
  25. use WebDriver\Exception as WebDriverException;
  26. /**
  27. * Abstract WebDriver\AbstractWebDriver class
  28. *
  29. * @package WebDriver
  30. */
  31. abstract class AbstractWebDriver
  32. {
  33. /**
  34. * URL
  35. *
  36. * @var string
  37. */
  38. protected $url;
  39. /**
  40. * Return array of supported method names and corresponding HTTP request methods
  41. *
  42. * @return array
  43. */
  44. abstract protected function methods();
  45. /**
  46. * Return array of obsolete method names and corresponding HTTP request methods
  47. *
  48. * @return array
  49. */
  50. protected function obsoleteMethods()
  51. {
  52. return array();
  53. }
  54. /**
  55. * Constructor
  56. *
  57. * @param string $url URL to Selenium server
  58. */
  59. public function __construct($url = 'http://localhost:4444/wd/hub')
  60. {
  61. $this->url = $url;
  62. }
  63. /**
  64. * Magic method which returns URL to Selenium server
  65. *
  66. * @return string
  67. */
  68. public function __toString()
  69. {
  70. return $this->url;
  71. }
  72. /**
  73. * Returns URL to Selenium server
  74. *
  75. * @return string
  76. */
  77. public function getURL()
  78. {
  79. return $this->url;
  80. }
  81. /**
  82. * Curl request to webdriver server.
  83. *
  84. * @param string $requestMethod HTTP request method, e.g., 'GET', 'POST', or 'DELETE'
  85. * @param string $command If not defined in methods() this function will throw.
  86. * @param array $parameters If an array(), they will be posted as JSON parameters
  87. * If a number or string, "/$params" is appended to url
  88. * @param array $extraOptions key=>value pairs of curl options to pass to curl_setopt()
  89. *
  90. * @return array array('value' => ..., 'info' => ...)
  91. *
  92. * @throws \WebDriver\Exception if error
  93. */
  94. protected function curl($requestMethod, $command, $parameters = null, $extraOptions = array())
  95. {
  96. if ($parameters && is_array($parameters) && $requestMethod !== 'POST') {
  97. throw WebDriverException::factory(
  98. WebDriverException::NO_PARAMETERS_EXPECTED,
  99. sprintf(
  100. 'The http request method called for %s is %s but it has to be POST if you want to pass the JSON parameters %s',
  101. $command,
  102. $requestMethod,
  103. json_encode($parameters)
  104. )
  105. );
  106. }
  107. $url = sprintf('%s%s', $this->url, $command);
  108. if ($parameters && (is_int($parameters) || is_string($parameters))) {
  109. $url .= '/' . $parameters;
  110. }
  111. list($rawResult, $info) = ServiceFactory::getInstance()->getService('service.curl')->execute($requestMethod, $url, $parameters, $extraOptions);
  112. $httpCode = $info['http_code'];
  113. // According to https://w3c.github.io/webdriver/webdriver-spec.html all 4xx responses are to be considered
  114. // an error and return plaintext, while 5xx responses are json encoded
  115. if ($httpCode >= 400 && $httpCode <= 499) {
  116. throw WebDriverException::factory(
  117. WebDriverException::CURL_EXEC,
  118. 'Webdriver http error: ' . $httpCode . ', payload :' . substr($rawResult, 0, 1000)
  119. );
  120. }
  121. $result = json_decode($rawResult, true);
  122. if (!empty($rawResult) && $result === null && json_last_error() != JSON_ERROR_NONE) {
  123. throw WebDriverException::factory(
  124. WebDriverException::CURL_EXEC,
  125. 'Payload received from webdriver is not valid json: ' . substr($rawResult, 0, 1000)
  126. );
  127. }
  128. if (is_array($result) && !array_key_exists('status', $result)) {
  129. throw WebDriverException::factory(
  130. WebDriverException::CURL_EXEC,
  131. 'Payload received from webdriver is valid but unexpected json: ' . substr($rawResult, 0, 1000)
  132. );
  133. }
  134. $value = (is_array($result) && array_key_exists('value', $result)) ? $result['value'] : null;
  135. $message = (is_array($value) && array_key_exists('message', $value)) ? $value['message'] : null;
  136. // if not success, throw exception
  137. if ((int) $result['status'] !== 0) {
  138. throw WebDriverException::factory($result['status'], $message);
  139. }
  140. $sessionId = isset($result['sessionId'])
  141. ? $result['sessionId']
  142. : (isset($value['webdriver.remote.sessionid'])
  143. ? $value['webdriver.remote.sessionid']
  144. : null
  145. );
  146. return array(
  147. 'value' => $value,
  148. 'info' => $info,
  149. 'sessionId' => $sessionId,
  150. 'sessionUrl' => $sessionId ? $this->url . '/session/' . $sessionId : $info['url'],
  151. );
  152. }
  153. /**
  154. * Magic method that maps calls to class methods to execute WebDriver commands
  155. *
  156. * @param string $name Method name
  157. * @param array $arguments Arguments
  158. *
  159. * @return mixed
  160. *
  161. * @throws \WebDriver\Exception if invalid WebDriver command
  162. */
  163. public function __call($name, $arguments)
  164. {
  165. if (count($arguments) > 1) {
  166. throw WebDriverException::factory(
  167. WebDriverException::JSON_PARAMETERS_EXPECTED,
  168. 'Commands should have at most only one parameter, which should be the JSON Parameter object'
  169. );
  170. }
  171. if (preg_match('/^(get|post|delete)/', $name, $matches)) {
  172. $requestMethod = strtoupper($matches[0]);
  173. $webdriverCommand = strtolower(substr($name, strlen($requestMethod)));
  174. } else {
  175. $webdriverCommand = $name;
  176. $requestMethod = $this->getRequestMethod($webdriverCommand);
  177. }
  178. $methods = $this->methods();
  179. if (!in_array($requestMethod, (array) $methods[$webdriverCommand])) {
  180. throw WebDriverException::factory(
  181. WebDriverException::INVALID_REQUEST,
  182. sprintf(
  183. '%s is not an available http request method for the command %s.',
  184. $requestMethod,
  185. $webdriverCommand
  186. )
  187. );
  188. }
  189. $result = $this->curl(
  190. $requestMethod,
  191. '/' . $webdriverCommand,
  192. array_shift($arguments)
  193. );
  194. return $result['value'];
  195. }
  196. /**
  197. * Get default HTTP request method for a given WebDriver command
  198. *
  199. * @param string $webdriverCommand
  200. *
  201. * @return string
  202. *
  203. * @throws \WebDriver\Exception if invalid WebDriver command
  204. */
  205. private function getRequestMethod($webdriverCommand)
  206. {
  207. if (!array_key_exists($webdriverCommand, $this->methods())) {
  208. throw WebDriverException::factory(
  209. array_key_exists($webdriverCommand, $this->obsoleteMethods())
  210. ? WebDriverException::OBSOLETE_COMMAND : WebDriverException::UNKNOWN_COMMAND,
  211. sprintf('%s is not a valid WebDriver command.', $webdriverCommand)
  212. );
  213. }
  214. $methods = $this->methods();
  215. $requestMethods = (array) $methods[$webdriverCommand];
  216. return array_shift($requestMethods);
  217. }
  218. }