Timeouts.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * Copyright 2011-2017 Anthon Pang. 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 Anthon Pang <apang@softwaredevelopment.ca>
  20. */
  21. namespace WebDriver;
  22. use WebDriver\Exception as WebDriverException;
  23. /**
  24. * WebDriver\Timeouts class
  25. *
  26. * @package WebDriver
  27. *
  28. * @method void async_script($json) Set the amount of time, in milliseconds, that asynchronous scripts (executed by execute_async) are permitted to run before they are aborted and a timeout error is returned to the client.
  29. * @method void implicit_wait($json) Set the amount of time the driver should wait when searching for elements.
  30. */
  31. final class Timeouts extends AbstractWebDriver
  32. {
  33. /**
  34. * {@inheritdoc}
  35. */
  36. protected function methods()
  37. {
  38. return array(
  39. 'async_script' => array('POST'),
  40. 'implicit_wait' => array('POST'),
  41. );
  42. }
  43. /**
  44. * helper method to wait until user-defined condition is met
  45. *
  46. * @param function $callback callback which returns non-false result if wait condition was met
  47. * @param integer $maxIterations maximum number of iterations
  48. * @param integer $sleep sleep duration in seconds between iterations
  49. * @param array $args optional args; if the callback needs $this, then pass it here
  50. *
  51. * @return mixed result from callback function
  52. *
  53. * @throws \Exception if thrown by callback, or \WebDriver\Exception\Timeout if helper times out
  54. */
  55. public function wait($callback, $maxIterations = 1, $sleep = 0, $args = array())
  56. {
  57. $i = max(1, $maxIterations);
  58. while ($i-- > 0) {
  59. $result = call_user_func_array($callback, $args);
  60. if ($result !== false) {
  61. return $result;
  62. }
  63. // don't sleep on the last iteration
  64. $i && sleep($sleep);
  65. }
  66. throw WebDriverException::factory(WebDriverException::TIMEOUT, 'wait() method timed out');
  67. }
  68. }