1<?php
2
3use dokuwiki\HTTP\HTTPClient;
4
5/**
6 * Class HTTPMockClient
7 *
8 * Does not really mock the client, it still does real connections but will retry failed connections
9 * to work around shaky connectivity.
10 */
11class HTTPMockClient extends HTTPClient {
12    protected $tries;
13    protected $lasturl;
14
15    /**
16     * Sets shorter timeout
17     */
18    public function __construct() {
19        parent::__construct();
20        $this->timeout = 8; // slightly faster timeouts
21    }
22
23    /**
24     * Returns true if the connection timed out
25     *
26     * @return bool
27     */
28    public function noconnection() {
29        return ($this->tries === 0);
30    }
31
32    /**
33     * Retries sending the request multiple times
34     *
35     * @param string $url
36     * @param string $data
37     * @param string $method
38     * @return bool
39     */
40    public function sendRequest($url, $data = '', $method = 'GET') {
41        $this->lasturl = $url;
42        $this->tries = 2; // configures the number of retries
43        $return      = false;
44        while($this->tries) {
45            $return = parent::sendRequest($url, $data, $method);
46            if($this->status != -100 && $this->status != 408) break;
47            usleep((3 - $this->tries) * 250000);
48            $this->tries--;
49        }
50        return $return;
51    }
52
53    /**
54     * Return detailed error data
55     *
56     * @param string $info optional additional info
57     * @return string
58     */
59    public function errorInfo($info = '') {
60        return json_encode(
61            array(
62                'URL' => $this->lasturl,
63                'Error' => $this->error,
64                'Status' => $this->status,
65                'Body' => $this->resp_body,
66                'Info' => $info
67            ), JSON_PRETTY_PRINT
68        );
69    }
70}
71