URLChecker.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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\Net;
  16. use Exception;
  17. use Facebook\WebDriver\Exception\TimeOutException;
  18. class URLChecker
  19. {
  20. const POLL_INTERVAL_MS = 500;
  21. const CONNECT_TIMEOUT_MS = 500;
  22. public function waitUntilAvailable($timeout_in_ms, $url)
  23. {
  24. $end = microtime(true) + $timeout_in_ms / 1000;
  25. while ($end > microtime(true)) {
  26. if ($this->getHTTPResponseCode($url) === 200) {
  27. return $this;
  28. }
  29. usleep(self::POLL_INTERVAL_MS);
  30. }
  31. throw new TimeOutException(sprintf(
  32. 'Timed out waiting for %s to become available after %d ms.',
  33. $url,
  34. $timeout_in_ms
  35. ));
  36. }
  37. public function waitUntilUnavailable($timeout_in_ms, $url)
  38. {
  39. $end = microtime(true) + $timeout_in_ms / 1000;
  40. while ($end > microtime(true)) {
  41. if ($this->getHTTPResponseCode($url) !== 200) {
  42. return $this;
  43. }
  44. usleep(self::POLL_INTERVAL_MS);
  45. }
  46. throw new TimeOutException(sprintf(
  47. 'Timed out waiting for %s to become unavailable after %d ms.',
  48. $url,
  49. $timeout_in_ms
  50. ));
  51. }
  52. private function getHTTPResponseCode($url)
  53. {
  54. $ch = curl_init();
  55. curl_setopt($ch, CURLOPT_URL, $url);
  56. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  57. // The PHP doc indicates that CURLOPT_CONNECTTIMEOUT_MS constant is added in cURL 7.16.2
  58. // available since PHP 5.2.3.
  59. if (!defined(CURLOPT_CONNECTTIMEOUT_MS)) {
  60. define('CURLOPT_CONNECTTIMEOUT_MS', 156); // default value for CURLOPT_CONNECTTIMEOUT_MS
  61. }
  62. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, self::CONNECT_TIMEOUT_MS);
  63. $code = null;
  64. try {
  65. curl_exec($ch);
  66. $info = curl_getinfo($ch);
  67. $code = $info['http_code'];
  68. } catch (Exception $e) {
  69. }
  70. curl_close($ch);
  71. return $code;
  72. }
  73. }