WebDriverWait.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. // Copyright 2004-present Facebook. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. namespace Facebook\WebDriver;
  16. use Facebook\WebDriver\Exception\NoSuchElementException;
  17. use Facebook\WebDriver\Exception\TimeOutException;
  18. /**
  19. * A utility class, designed to help the user to wait until a condition turns true.
  20. *
  21. * @see WebDriverExpectedCondition.
  22. */
  23. class WebDriverWait
  24. {
  25. /**
  26. * @var WebDriver
  27. */
  28. protected $driver;
  29. /**
  30. * @var int
  31. */
  32. protected $timeout;
  33. /**
  34. * @var int
  35. */
  36. protected $interval;
  37. public function __construct(WebDriver $driver, $timeout_in_second = null, $interval_in_millisecond = null)
  38. {
  39. $this->driver = $driver;
  40. $this->timeout = isset($timeout_in_second) ? $timeout_in_second : 30;
  41. $this->interval = $interval_in_millisecond ?: 250;
  42. }
  43. /**
  44. * Calls the function provided with the driver as an argument until the return value is not falsey.
  45. *
  46. * @param callable|WebDriverExpectedCondition $func_or_ec
  47. * @param string $message
  48. *
  49. * @throws NoSuchElementException
  50. * @throws TimeOutException
  51. * @throws \Exception
  52. * @return mixed The return value of $func_or_ec
  53. */
  54. public function until($func_or_ec, $message = '')
  55. {
  56. $end = microtime(true) + $this->timeout;
  57. $last_exception = null;
  58. while ($end > microtime(true)) {
  59. try {
  60. if ($func_or_ec instanceof WebDriverExpectedCondition) {
  61. $ret_val = call_user_func($func_or_ec->getApply(), $this->driver);
  62. } else {
  63. $ret_val = call_user_func($func_or_ec, $this->driver);
  64. }
  65. if ($ret_val) {
  66. return $ret_val;
  67. }
  68. } catch (NoSuchElementException $e) {
  69. $last_exception = $e;
  70. }
  71. usleep($this->interval * 1000);
  72. }
  73. if ($last_exception) {
  74. throw $last_exception;
  75. }
  76. throw new TimeOutException($message);
  77. }
  78. }