Curl::__clone()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * This file is part of Communique.
5
 * 
6
 * @author Robert Main
7
 * @package Communique
8
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Communique;
15
16
/**
17
 * cURL Class
18
 *
19
 * This class is used to provide an object wrapper around cURL
20
 * 
21
 * @codeCoverageIgnore
22
 */
23
class Curl {
24
25
	/**
26
	 * A cURL handle created when the object is constructed
27
	 * @var resource
28
	 */
29
	private $_ch = null;
30
31
	/**
32
	 * Constructs the cURL object wrapper
33
	 * @throws \Communique\CommuniqueRESTConnectionException
34
	 */
35
	public function __construct() {
36
		if (!extension_loaded('curl')) {
37
			throw new \Communique\CommuniqueRESTConnectionException('cURL Error: ' . $this->error() . ' cURL Error Code: ' . $this->errno());
38
		} else {
39
			$this->_ch = curl_init();
40
			$this->setopt(CURLOPT_CAINFO, \Kdyby\CurlCaBundle\CertificateHelper::getCaInfoFile());
41
		}
42
	}
43
44
	/**
45
	 * Called when the object is garbage collected. This method basically just closes the cURL handle.
46
	 */
47
	public function __destruct() {
48
		if ($this->_ch !== null) {
49
			curl_close($this->_ch);
50
		}
51
	}
52
53
	/**
54
	 * Called when the object is copied using the `clone` operator.
55
	 * 
56
	 * Copies the current cURL handle and sets the value returned from `curl_copy_handle()` as the value of `$this->_ch` 
57
	 */
58
	public function __clone() {
59
		$this->_ch = curl_copy_handle($this->_ch);
60
	}
61
62
	/**
63
	 * Converts a string containing multiple headers into an array that can be used programatically.
64
	 * @param  string $headerContent A header string
65
	 * @return array An indexable array of headers
66
	 */
67
	private static function headers_to_array($headerContent) {
68
		$headers = array();
69
		$arrRequests = explode("\r\n\r\n", $headerContent);
70
		foreach (explode("\r\n", $arrRequests[0]) as $i => $line) {
71
			if ($i === 0) {
72
				$headers['http_code'] = $line;
73
			} else {
74
				list($key, $value) = explode(': ', $line);
75
				$headers[$key] = $value;
76
			}
77
		}
78
		return $headers;
79
	}
80
81
	/**
82
	 * Gets cURL version information
83
	 * @see  http://php.net/manual/en/function.curl-version.php Official PHP documentation for curl_version()
84
	 * @param  int $age 
85
	 * @return array Returns an asociative array with information regarding the version of cURL in question
86
	 */
87
	public static function version($age = CURLVERSION_NOW) {
88
		return curl_version($age);
89
	}
90
91
	/**
92
	 * Return string describing the given error code
93
	 * @see  http://php.net/manual/en/function.curl-strerror.php Official PHP documentation for curl_strerror()
94
	 * @param  int $errornum One of the [cURL error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html) constants
95
	 * @return string Returns error description or NULL for invalid error code.
96
	 */
97
	public static function strerror($errornum) {
98
		return curl_strerror($errornum);
99
	}
100
101
	/**
102
	 * Create a CURLFile object
103
	 * @see  http://php.net/manual/en/function.curl-file-create.php Official PHP documentation for curl_file_create()
104
	 * @param  string $filename Path to the file which will be uploaded
105
	 * @param  string $mimetype Mimetype of the file
106
	 * @param  string $postname Name of the file to be used in the upload data
107
	 * @return \CURLFile           Returns a CURLFile object
108
	 */
109
	public static function file_create($filename, $mimetype = '', $postname = '') {
110
		return curl_file_create($filename, $mimetype, $postname);
111
	}
112
113
	/**
114
	 * Return the last error number
115
	 * @see  http://php.net/manual/en/function.curl-errno.php Official PHP documentation for curl_errno()
116
	 * @return int Returns the error number or 0 (zero) if no error ocurred.
117
	 */
118
	public function errno() {
119
		return curl_errno($this->_ch);
120
	}
121
122
	/**
123
	 * Return a a string containing the last error for the current session
124
	 * @see  http://php.net/manual/en/function.curl-error.php Official PHP documentation for curl_error()
125
	 * @return string Returns the error message or "" (the empty string) if no error ocurred
126
	 */
127
	public function error() {
128
		return curl_error($this->_ch);
129
	}
130
131
	/**
132
	 * URL encodes the given string
133
	 * @see http://php.net/manual/en/function.curl-escape.php Official PHP documentation for curl_escape()
134
	 * @param  string $str The string to be encoded
135
	 * @return string|boolean Returns escaped string or **FALSE** on failiure
136
	 */
137
	public function escape($str) {
138
		return curl_escape($this->_ch, $str);
139
	}
140
141
	/**
142
	 * This function should be called after initializing a cURL session and all the options for the session are set
143
	 * @see http://php.net/manual/en/function.curl-exec.php Official PHP documentation for curl_exec()
144
	 * @return boolean|mixed     Returns **TRUE** on success or **FALSE** on failiure. However, if the **CURLOPT_RETURNTANSFER** option is set, it will return the result on success, **FALSE** on failiure	 
145
	 */
146
	public function exec() {
147
		if ($response = curl_exec($this->_ch)) {
148
			$header_size = $this->getinfo(CURLINFO_HEADER_SIZE);
149
			return array(
150
				'http_status_code' => $this->getinfo(CURLINFO_HTTP_CODE),
151
				'body' => substr($response, $header_size),
152
				'headers' => self::headers_to_array(substr($response, 0, $header_size))
153
			);
154
		} else {
155
			return false;
156
		}
157
	}
158
159
	/**
160
	 * Get information regarding a specific transfer
161
	 * @see  http://php.net/manual/en/function.curl-getinfo.php Official PHP documentation for curl_getinfo()
162
	 * @param  integer $opt This may be one of the following constants:
163
	 * 1. **CURLINFO_EFFECTIVE_URL** - Last effective URL
164
	 * 1. **CURLINFO_HTTP_CODE** - Last received HTTP code
165
	 * 1. **CURLINFO_FILETIME** - Remote time of the retrieved document, if -1 is returned the time of the document is unknown
166
	 * 1. **CURLINFO_TOTAL_TIME** - Total transaction time in seconds for last transfer
167
	 * 1. **CURLINFO_NAMELOOKUP_TIME** - Time in seconds until name resolving was complete
168
	 * 1. **CURLINFO_CONNECT_TIME** - Time in seconds it took to establish the connection
169
	 * 1. **CURLINFO_PRETRANSFER_TIME** - Time in seconds from start until just before file transfer begins
170
	 * 1. **CURLINFO_STARTTRANSFER_TIME** - Time in seconds until the first byte is about to be transferred
171
	 * 1. **CURLINFO_REDIRECT_COUNT** - Number of redirects, with the CURLOPT_FOLLOWLOCATION option enabled
172
	 * 1. **CURLINFO_REDIRECT_TIME** - Time in seconds of all redirection steps before final transaction was started, with the CURLOPT_FOLLOWLOCATION option enabled
173
	 * 1. **CURLINFO_REDIRECT_URL** - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL
174
	 * 1. **CURLINFO_PRIMARY_IP** - IP address of the most recent connection
175
	 * 1. **CURLINFO_PRIMARY_PORT** - Destination port of the most recent connection
176
	 * 1. **CURLINFO_LOCAL_IP** - Local (source) IP address of the most recent connection
177
	 * 1. **CURLINFO_LOCAL_PORT** - Local (source) port of the most recent connection
178
	 * 1. **CURLINFO_SIZE_UPLOAD** - Total number of bytes uploaded
179
	 * 1. **CURLINFO_SIZE_DOWNLOAD** - Total number of bytes downloaded
180
	 * 1. **CURLINFO_SPEED_DOWNLOAD** - Average download speed
181
	 * 1. **CURLINFO_SPEED_UPLOAD** - Average upload speed
182
	 * 1. **CURLINFO_HEADER_SIZE** - Total size of all headers received
183
	 * 1. **CURLINFO_HEADER_OUT** - The request string sent. For this to work, add the CURLINFO_HEADER_OUT option to the handle by calling setopt()
184
	 * 1. **CURLINFO_REQUEST_SIZE** - Total size of issued requests, currently only for HTTP requests
185
	 * 1. **CURLINFO_SSL_VERIFYRESULT** - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER
186
	 * 1. **CURLINFO_CONTENT_LENGTH_DOWNLOAD** - content-length of download, read from Content-Length: field
187
	 * 1. **CURLINFO_CONTENT_LENGTH_UPLOAD** - Specified size of upload
188
	 * 1. **CURLINFO_CONTENT_TYPE** - Content-Type: of the requested document, NULL indicates server did not send valid Content-Type: header
189
	 * 1. **CURLINFO_PRIVATE** - Private data associated with this cURL handle, previously set with the CURLOPT_PRIVATE option of setopt()
190
	 * @return mixed|array|boolean   If **opt** is given, returns it's value. Otherwise, returns an associative array with the following elements(which correspond to **opt**), or **FALSE** on failiure:  
191
	 * - "url"
192
	 * - "content_type"
193
	 * - "http_code"
194
	 * - "header_size"
195
	 * - "request_size"
196
	 * - "filetime"
197
	 * - "ssl_verify_result"
198
	 * - "redirect_count"
199
	 * - "total_time"
200
	 * - "namelookup_time"
201
	 * - "connect_time"
202
	 * - "pretransfer_time"
203
	 * - "size_upload"
204
	 * - "size_download"
205
	 * - "speed_download"
206
	 * - "speed_upload"
207
	 * - "download_content_length"
208
	 * - "upload_content_length"
209
	 * - "starttransfer_time"
210
	 * - "redirect_time"
211
	 * - "certinfo"
212
	 * - "primary_ip"
213
	 * - "primary_port"
214
	 * - "local_ip"
215
	 * - "local_port"
216
	 * - "redirect_url"
217
	 * - "request_header" (This is only set if the **CURLINFO_HEADER_OUT** is set by a previous call to setopt())
218
	 */
219
	public function getinfo($opt = 0) {
220
		return curl_getinfo($this->_ch, $opt);
221
	}
222
223
	/**
224
	 * Pause and unpause a connection
225
	 * @see  http://php.net/manual/en/function.curl-pause.php Official PHP documentation for curl_pause()
226
	 * @param  int $bitmask One of the **CURLPAUSE_\*** constants
227
	 * @return int Returns an error code (**CURLE_OK** for no error)
228
	 */
229
	public function pause($bitmask) {
230
		return curl_pause($this->_ch, $bitmask);
231
	}
232
233
234
	/**
235
	 * Set multiple options for a cURL transfer
236
	 * @see  http://php.net/manual/en/function.curl-setopt-array.php Official PHP documentation for curl_setopt_array()
237
	 * @param  array $options An array specifying which options to set and their values. The keys should be valid curl_setopt() constants or their integer equivalents.
238
	 * @return boolean Returns **TRUE** if all options were successfully set. If an option could not be successfully set, **FALSE** is immediately returned, ignoring any future options in the `$options` array.
239
	 */
240
	public function setopt_array($options) {
241
		return curl_setopt_array($this->_ch, $options);
242
	}
243
244
	/**
245
	 * Set an option for a cURL transfer
246
	 * @see  http://php.net/manual/en/function.curl-setopt.php Official PHP documentation for curl_setopt()
247
	 * @param  int $option The **CURLOPT_XXX**
248
	 * @param  integer $value The value to be set on option
249
	 * @return boolean Returns **TRUE** on success or **FALSE** on failure.
250
	 */
251
	public function setopt($option, $value) {
252
		return curl_setopt($this->_ch, $option, $value);
253
	}
254
255
	/**
256
	 * Decodes the given URL encoded string
257
	 * @see  http://php.net/manual/en/function.curl-unescape.php Official PHP documentation for curl_unescape()
258
	 * @param  string $str The URL encoded string to be decoded
259
	 * @return string Returned decoded string or **FALSE** on failiure
260
	 */
261
	public function unescape($str) {
262
		return curl_unescape($this->_ch, $str);
263
	}
264
265
	/**
266
	 * Reset all options of a libcurl session handle
267
	 */
268
	public function reset() {
269
		curl_reset($this->_ch);
270
	}
271
}