CurlRequest::reallyMakeRequest()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 35
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 23
nc 7
nop 1
dl 0
loc 35
rs 9.2408
c 0
b 0
f 0
1
<?php declare( strict_types=1 );
2
3
namespace BotRiconferme\Request;
4
5
use BotRiconferme\Exception\APIRequestException;
6
use BotRiconferme\Exception\TimeoutException;
7
8
/**
9
 * Request done using cURL, if available
10
 */
11
class CurlRequest extends RequestBase {
12
	/**
13
	 * @inheritDoc
14
	 * @throws APIRequestException
15
	 */
16
	protected function reallyMakeRequest( string $params ): string {
17
		$curl = curl_init();
18
		if ( $curl === false ) {
19
			throw new APIRequestException( 'Cannot open cURL handler.' );
20
		}
21
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
22
		curl_setopt( $curl, CURLOPT_HEADER, true );
23
		curl_setopt( $curl, CURLOPT_HEADERFUNCTION, [ $this, 'headersHandler' ] );
24
		curl_setopt( $curl, CURLOPT_HTTPHEADER, $this->getHeaders() );
25
26
		if ( $this->method === self::METHOD_POST ) {
27
			curl_setopt( $curl, CURLOPT_URL, $this->url );
28
			curl_setopt( $curl, CURLOPT_POST, true );
29
			curl_setopt( $curl, CURLOPT_POSTFIELDS, $params );
30
		} else {
31
			curl_setopt( $curl, CURLOPT_URL, "{$this->url}?$params" );
32
		}
33
34
		$result = curl_exec( $curl );
35
36
		if ( $result === false ) {
37
			$debugUrl = $this->getDebugURL( $params );
38
			if ( curl_errno( $curl ) === CURLE_OPERATION_TIMEDOUT ) {
39
				throw new TimeoutException( "Curl timeout for $debugUrl" );
40
			}
41
			throw new APIRequestException( "Curl error for $debugUrl: " . curl_error( $curl ) );
42
		}
43
44
		// Extract response body
45
		$headerSize = curl_getinfo( $curl, CURLINFO_HEADER_SIZE );
46
		/** @var string $result Because RETURNTRANSFER is set */
47
		$body = substr( $result, $headerSize );
48
		curl_close( $curl );
49
50
		return $body;
51
	}
52
53
	/**
54
	 * cURL's headers handler
55
	 *
56
	 * @param resource $ch TODO CurlHandle on PHP 8
57
	 * @param string $header
58
	 * @return int
59
	 * @internal Only used as CB for cURL (CURLOPT_HEADERFUNCTION)
60
	 * @suppress PhanUnreferencedPublicMethod,PhanUnusedPublicNoOverrideMethodParameter
61
	 */
62
	public function headersHandler( $ch, string $header ): int {
63
		$this->handleResponseHeader( $header );
64
		return strlen( $header );
65
	}
66
}
67