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