Completed
Push — master ( b042a4...d2fe3d )
by Josh
17:24
created

Curl::getHandle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6667
cc 2
eloc 4
nc 2
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\Configurator\Helpers\Http\Clients;
9
10
use s9e\TextFormatter\Configurator\Helpers\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 2
	public function get($url, $headers = [])
23
	{
24 2
		$handle = $this->getHandle();
25 2
		curl_setopt($handle, CURLOPT_HTTPGET,    true);
26 2
		curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
27 2
		curl_setopt($handle, CURLOPT_URL,        $url);
28
29 2
		return curl_exec($handle);
30
	}
31
32
	/**
33
	* {@inheritdoc}
34
	*/
35 2
	public function post($url, $headers = [], $body = null)
36
	{
37 2
		$handle = $this->getHandle();
38 2
		if (isset($body))
39 2
		{
40 2
			curl_setopt($handle, CURLOPT_POSTFIELDS, $body);
41 2
			$headers[] = 'Content-Length: ' . strlen($body);
42 2
		}
43 2
		curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
44 2
		curl_setopt($handle, CURLOPT_POST,       true);
45 2
		curl_setopt($handle, CURLOPT_URL,        $url);
46
47 2
		return curl_exec($handle);
48
	}
49
50
	/**
51
	* Return a globally cached cURL handle
52
	*
53
	* @return resource
54
	*/
55 4
	protected function getHandle()
56
	{
57 4
		if (!isset(self::$handle))
58 4
		{
59 1
			self::$handle = $this->getNewHandle();
60 1
		}
61
62 4
		return self::$handle;
63
	}
64
65
	/**
66
	* Create and return a new cURL handle
67
	*
68
	* @return resource
69
	*/
70 1
	protected function getNewHandle()
71
	{
72 1
		$handle = curl_init();
73 1
		curl_setopt($handle, CURLOPT_ENCODING,       '');
74 1
		curl_setopt($handle, CURLOPT_FAILONERROR,    true);
75 1
		curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
76 1
		curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
77
78 1
		return $handle;
79
	}
80
}