Http::request()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 14
rs 9.4285
cc 3
eloc 9
nc 3
nop 2
1
<?php
2
3
namespace Asparagus;
4
5
use RuntimeException;
6
7
/**
8
 * Package-private class to deal with HTTP related stuff.
9
 *
10
 * @license GNU GPL v2+
11
 * @author Bene* < [email protected] >
12
 */
13
class Http {
14
15
	/**
16
	 * @var resource cURL-Handle
17
	 */
18
	private $ch;
19
20
	/**
21
	 * @param string $userAgent
22
	 */
23
	public function __construct( $userAgent ) {
24
		$this->ch = curl_init();
25
		curl_setopt( $this->ch, CURLOPT_USERAGENT, $userAgent );
26
		curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, true );
27
		curl_setopt( $this->ch, CURLOPT_FOLLOWLOCATION, true );
28
	}
29
30
	public function __destruct() {
31
		curl_close( $this->ch );
32
	}
33
34
	/**
35
	 * @param string $url
36
	 * @param string[] $params
37
	 * @return string
38
	 * @throws RuntimeException
39
	 */
40
	public function request( $url, array $params = array() ) {
41
		curl_setopt( $this->ch, CURLOPT_URL, $url . '?' . http_build_query( $params ) );
42
		curl_setopt( $this->ch, CURLOPT_HTTPGET, true );
43
44
		$response = curl_exec( $this->ch );
45
46
		if ( curl_errno( $this->ch ) ) {
47
			throw new RuntimeException( curl_error( $this->ch ), curl_errno( $this->ch ) );
48
		} else if ( curl_getinfo( $this->ch, CURLINFO_HTTP_CODE ) >= 400 ) {
49
			throw new RuntimeException( 'HTTP error: ' . $url, curl_getinfo( $this->ch, CURLINFO_HTTP_CODE ) );
50
		}
51
52
		return $response;
53
	}
54
55
}
56