Passed
Push — master ( cf401d...252787 )
by Michael
02:49
created

AbstractService::makeHTTPRequest()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 11
nc 4
nop 5
dl 0
loc 17
rs 8.2222
c 0
b 0
f 0
1
<?php
2
3
namespace dokuwiki\plugin\issuelinks\services;
4
5
use dokuwiki\plugin\issuelinks\classes\ExternalServerException;
6
use dokuwiki\plugin\issuelinks\classes\HTTPRequestException;
7
8
abstract class AbstractService implements ServiceInterface
9
{
10
    protected static $instance = [];
11
12
    public static function getInstance($forcereload = false)
13
    {
14
        $class = static::class;
15
        if (empty(self::$instance[$class]) || $forcereload) {
16
            self::$instance[$class] = new $class();
17
        }
18
        return self::$instance[$class];
19
    }
20
21
    /**
22
     * Make an http request
23
     *
24
     * Throws an exception on errer or if the request was not successful
25
     *
26
     * You can query the $dokuHTTPClient for more result headers later
27
     *
28
     * @param \DokuHTTPClient $dokuHTTPClient an Instance of \DokuHTTPClient which will make the request
29
     * @param string          $url            the complete URL to which to make the request
30
     * @param array           $headers        This headers will be merged with the headers in the DokuHTTPClient
31
     * @param array           $data           an array of the data which is to be send
32
     * @param string          $method         a HTTP verb, like GET, POST or DELETE
33
     *
34
     * @return array the result that was returned from the server, json-decoded
35
     *
36
     * @throws HTTPRequestException
37
     */
38
    protected function makeHTTPRequest(\DokuHTTPClient $dokuHTTPClient, $url, $headers, array $data, $method)
39
    {
40
        $dokuHTTPClient->headers = array_merge($dokuHTTPClient->headers ?: [], $headers);
41
        $dataToBeSend = json_encode($data);
42
        try {
43
            $success = $dokuHTTPClient->sendRequest($url, $dataToBeSend, $method);
44
        } catch (\HTTPClientException $e) {
45
            throw new HTTPRequestException('request error', $dokuHTTPClient, $url, $method);
46
        }
47
48
        if (!$success || $dokuHTTPClient->status < 200 || $dokuHTTPClient->status > 206) {
49
            if ($dokuHTTPClient->status >= 500) {
50
                throw new ExternalServerException('request error', $dokuHTTPClient, $url, $method);
51
            }
52
            throw new HTTPRequestException('request error', $dokuHTTPClient, $url, $method);
53
        }
54
        return json_decode($dokuHTTPClient->resp_body, true);
55
    }
56
57
}
58