Completed
Push — master ( 5feeae...0d739f )
by Josh
18:19 queued 12:34
created

Curl::getNewHandle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 7
cp 0
rs 9.4286
cc 1
eloc 7
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2016 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Utils\Http\Clients;
9
10
use s9e\TextFormatter\Utils\Http\Client;
11
12
class Curl extends Client
13
{
14
	/**
15
	* @var resource cURL handle, shared across instances
16
	*/
17
	protected static $handle;
18
19
	/**
20
	* {@inheritdoc}
21
	*/
22 3
	public function get($url, $headers = [])
23
	{
24 3
		$handle = $this->getHandle();
25 3
		curl_setopt($handle, CURLOPT_HTTPGET,    true);
26 3
		curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
27 3
		curl_setopt($handle, CURLOPT_URL,        $url);
28
29 3
		return curl_exec($handle);
30
	}
31
32
	/**
33
	* {@inheritdoc}
34
	*/
35 3
	public function post($url, $headers = [], $body = '')
36
	{
37 3
		$headers[] = 'Content-Length: ' . strlen($body);
38
39 3
		$handle = $this->getHandle();
40 3
		curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
41 3
		curl_setopt($handle, CURLOPT_POST,       true);
42 3
		curl_setopt($handle, CURLOPT_POSTFIELDS, $body);
43 3
		curl_setopt($handle, CURLOPT_URL,        $url);
44
45 3
		return curl_exec($handle);
46
	}
47
48
	/**
49
	* Return a globally cached cURL handle, configured for current instance
50
	*
51
	* @return resource
52
	*/
53 6
	protected function getHandle()
54
	{
55 6
		if (!isset(self::$handle))
56 6
		{
57
			self::$handle = $this->getNewHandle();
58
		}
59
60 6
		curl_setopt(self::$handle, CURLOPT_SSL_VERIFYPEER, $this->sslVerifyPeer);
61 6
		curl_setopt(self::$handle, CURLOPT_TIMEOUT,        $this->timeout);
62
63 6
		return self::$handle;
64
	}
65
66
	/**
67
	* Create and return a new cURL handle
68
	*
69
	* @return resource
70
	*/
71
	protected function getNewHandle()
72
	{
73
		$handle = curl_init();
74
		curl_setopt($handle, CURLOPT_ENCODING,       '');
75
		curl_setopt($handle, CURLOPT_FAILONERROR,    true);
76
		curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
77
		curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
78
79
		return $handle;
80
	}
81
}