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