Builder.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php namespace Ixudra\Curl;
  2. use stdClass;
  3. class Builder {
  4. /** @var resource $curlObject cURL request */
  5. protected $curlObject = null;
  6. /** @var array $curlOptions Array of cURL options */
  7. protected $curlOptions = array(
  8. 'RETURNTRANSFER' => true,
  9. 'FAILONERROR' => false,
  10. 'FOLLOWLOCATION' => false,
  11. 'CONNECTTIMEOUT' => '',
  12. 'TIMEOUT' => 30,
  13. 'USERAGENT' => '',
  14. 'URL' => '',
  15. 'POST' => false,
  16. 'HTTPHEADER' => array(),
  17. );
  18. /** @var array $packageOptions Array with options that are not specific to cURL but are used by the package */
  19. protected $packageOptions = array(
  20. 'data' => array(),
  21. 'asJsonRequest' => false,
  22. 'asJsonResponse' => false,
  23. 'returnAsArray' => false,
  24. 'responseObject' => false,
  25. 'enableDebug' => false,
  26. 'containsFile' => false,
  27. 'debugFile' => '',
  28. 'saveFile' => '',
  29. );
  30. /**
  31. * Set the URL to which the request is to be sent
  32. *
  33. * @param $url string The URL to which the request is to be sent
  34. * @return Builder
  35. */
  36. public function to($url)
  37. {
  38. return $this->withCurlOption( 'URL', $url );
  39. }
  40. /**
  41. * Set the request timeout
  42. *
  43. * @param integer $timeout The timeout for the request (in seconds. Default: 30 seconds)
  44. * @return Builder
  45. */
  46. public function withTimeout($timeout = 30)
  47. {
  48. return $this->withCurlOption( 'TIMEOUT', $timeout );
  49. }
  50. /**
  51. * Add GET or POST data to the request
  52. *
  53. * @param array $data Array of data that is to be sent along with the request
  54. * @return Builder
  55. */
  56. public function withData($data = array())
  57. {
  58. return $this->withPackageOption( 'data', $data );
  59. }
  60. /**
  61. * Allow for redirects in the request
  62. *
  63. * @return Builder
  64. */
  65. public function allowRedirect()
  66. {
  67. return $this->withCurlOption( 'FOLLOWLOCATION', true );
  68. }
  69. /**
  70. * Configure the package to encode and decode the request data
  71. *
  72. * @param boolean $asArray Indicates whether or not the data should be returned as an array. Default: false
  73. * @return Builder
  74. */
  75. public function asJson($asArray = false)
  76. {
  77. return $this->asJsonRequest()
  78. ->asJsonResponse( $asArray );
  79. }
  80. /**
  81. * Configure the package to encode the request data to json before sending it to the server
  82. *
  83. * @return Builder
  84. */
  85. public function asJsonRequest()
  86. {
  87. return $this->withPackageOption( 'asJsonRequest', true );
  88. }
  89. /**
  90. * Configure the package to decode the request data from json to object or associative array
  91. *
  92. * @param boolean $asArray Indicates whether or not the data should be returned as an array. Default: false
  93. * @return Builder
  94. */
  95. public function asJsonResponse($asArray = false)
  96. {
  97. return $this->withPackageOption( 'asJsonResponse', true )
  98. ->withPackageOption( 'returnAsArray', $asArray );
  99. }
  100. // /**
  101. // * Send the request over a secure connection
  102. // *
  103. // * @return Builder
  104. // */
  105. // public function secure()
  106. // {
  107. // return $this;
  108. // }
  109. /**
  110. * Set any specific cURL option
  111. *
  112. * @param string $key The name of the cURL option
  113. * @param string $value The value to which the option is to be set
  114. * @return Builder
  115. */
  116. public function withOption($key, $value)
  117. {
  118. return $this->withCurlOption( $key, $value );
  119. }
  120. /**
  121. * Set Cookie File
  122. *
  123. * @param string $cookieFile File name to read cookies from
  124. * @return Builder
  125. */
  126. public function setCookieFile($cookieFile)
  127. {
  128. return $this->withOption( 'COOKIEFILE', $cookieFile );
  129. }
  130. /**
  131. * Set Cookie Jar
  132. *
  133. * @param string $cookieJar File name to store cookies to
  134. * @return Builder
  135. */
  136. public function setCookieJar($cookieJar)
  137. {
  138. return $this->withOption( 'COOKIEJAR', $cookieJar );
  139. }
  140. /**
  141. * Set any specific cURL option
  142. *
  143. * @param string $key The name of the cURL option
  144. * @param string $value The value to which the option is to be set
  145. * @return Builder
  146. */
  147. protected function withCurlOption($key, $value)
  148. {
  149. $this->curlOptions[ $key ] = $value;
  150. return $this;
  151. }
  152. /**
  153. * Set any specific package option
  154. *
  155. * @param string $key The name of the cURL option
  156. * @param string $value The value to which the option is to be set
  157. * @return Builder
  158. */
  159. protected function withPackageOption($key, $value)
  160. {
  161. $this->packageOptions[ $key ] = $value;
  162. return $this;
  163. }
  164. /**
  165. * Add a HTTP header to the request
  166. *
  167. * @param string $header The HTTP header that is to be added to the request
  168. * @return Builder
  169. */
  170. public function withHeader($header)
  171. {
  172. $this->curlOptions[ 'HTTPHEADER' ][] = $header;
  173. return $this;
  174. }
  175. /**
  176. * Add multiple HTTP header at the same time to the request
  177. *
  178. * @param array $headers Array of HTTP headers that must be added to the request
  179. * @return Builder
  180. */
  181. public function withHeaders(array $headers)
  182. {
  183. $this->curlOptions[ 'HTTPHEADER' ] = array_merge(
  184. $this->curlOptions[ 'HTTPHEADER' ], $headers
  185. );
  186. return $this;
  187. }
  188. /**
  189. * Add a content type HTTP header to the request
  190. *
  191. * @param string $contentType The content type of the file you would like to download
  192. * @return Builder
  193. */
  194. public function withContentType($contentType)
  195. {
  196. return $this->withHeader( 'Content-Type: '. $contentType )
  197. ->withHeader( 'Connection: Keep-Alive' );
  198. }
  199. /**
  200. * Return a full response object with HTTP status and headers instead of only the content
  201. *
  202. * @return Builder
  203. */
  204. public function returnResponseObject()
  205. {
  206. return $this->withPackageOption( 'responseObject', true );
  207. }
  208. /**
  209. * Enable debug mode for the cURL request
  210. *
  211. * @param string $logFile The full path to the log file you want to use
  212. * @return Builder
  213. */
  214. public function enableDebug($logFile)
  215. {
  216. return $this->withPackageOption( 'enableDebug', true )
  217. ->withPackageOption( 'debugFile', $logFile )
  218. ->withOption( 'VERBOSE', true );
  219. }
  220. /**
  221. * Enable File sending
  222. *
  223. * @return Builder
  224. */
  225. public function containsFile()
  226. {
  227. return $this->withPackageOption( 'containsFile', true );
  228. }
  229. /**
  230. * Send a GET request to a URL using the specified cURL options
  231. *
  232. * @return mixed
  233. */
  234. public function get()
  235. {
  236. $this->appendDataToURL();
  237. return $this->send();
  238. }
  239. /**
  240. * Send a POST request to a URL using the specified cURL options
  241. *
  242. * @return mixed
  243. */
  244. public function post()
  245. {
  246. $this->setPostParameters();
  247. return $this->send();
  248. }
  249. /**
  250. * Send a download request to a URL using the specified cURL options
  251. *
  252. * @param string $fileName
  253. * @return mixed
  254. */
  255. public function download($fileName)
  256. {
  257. $this->packageOptions[ 'saveFile' ] = $fileName;
  258. return $this->send();
  259. }
  260. /**
  261. * Add POST parameters to the curlOptions array
  262. */
  263. protected function setPostParameters()
  264. {
  265. $this->curlOptions[ 'POST' ] = true;
  266. $parameters = $this->packageOptions[ 'data' ];
  267. if( $this->packageOptions[ 'asJsonRequest' ] ) {
  268. $parameters = json_encode($parameters);
  269. }
  270. $this->curlOptions[ 'POSTFIELDS' ] = $parameters;
  271. }
  272. /**
  273. * Send a PUT request to a URL using the specified cURL options
  274. *
  275. * @return mixed
  276. */
  277. public function put()
  278. {
  279. $this->setPostParameters();
  280. return $this->withOption('CUSTOMREQUEST', 'PUT')
  281. ->send();
  282. }
  283. /**
  284. * Send a PATCH request to a URL using the specified cURL options
  285. *
  286. * @return mixed
  287. */
  288. public function patch()
  289. {
  290. $this->setPostParameters();
  291. return $this->withOption('CUSTOMREQUEST', 'PATCH')
  292. ->send();
  293. }
  294. /**
  295. * Send a DELETE request to a URL using the specified cURL options
  296. *
  297. * @return mixed
  298. */
  299. public function delete()
  300. {
  301. $this->appendDataToURL();
  302. return $this->withOption('CUSTOMREQUEST', 'DELETE')
  303. ->send();
  304. }
  305. /**
  306. * Send the request
  307. *
  308. * @return mixed
  309. */
  310. protected function send()
  311. {
  312. // Add JSON header if necessary
  313. if( $this->packageOptions[ 'asJsonRequest' ] ) {
  314. $this->withHeader( 'Content-Type: application/json' );
  315. }
  316. if( $this->packageOptions[ 'enableDebug' ] ) {
  317. $debugFile = fopen( $this->packageOptions[ 'debugFile' ], 'w');
  318. $this->withOption('STDERR', $debugFile);
  319. }
  320. // Create the request with all specified options
  321. $this->curlObject = curl_init();
  322. $options = $this->forgeOptions();
  323. curl_setopt_array( $this->curlObject, $options );
  324. // Send the request
  325. $response = curl_exec( $this->curlObject );
  326. // Capture additional request information if needed
  327. $responseData = array();
  328. if( $this->packageOptions[ 'responseObject' ] ) {
  329. $responseData = curl_getinfo( $this->curlObject );
  330. if( curl_errno($this->curlObject) ) {
  331. $responseData[ 'errorMessage' ] = curl_error($this->curlObject);
  332. }
  333. }
  334. curl_close( $this->curlObject );
  335. if( $this->packageOptions[ 'saveFile' ] ) {
  336. // Save to file if a filename was specified
  337. $file = fopen($this->packageOptions[ 'saveFile' ], 'w');
  338. fwrite($file, $response);
  339. fclose($file);
  340. } else if( $this->packageOptions[ 'asJsonResponse' ] ) {
  341. // Decode the request if necessary
  342. $response = json_decode($response, $this->packageOptions[ 'returnAsArray' ]);
  343. }
  344. if( $this->packageOptions[ 'enableDebug' ] ) {
  345. fclose( $debugFile );
  346. }
  347. // Return the result
  348. return $this->returnResponse( $response, $responseData );
  349. }
  350. /**
  351. * @param mixed $content Content of the request
  352. * @param array $responseData Additional response information
  353. * @return stdClass
  354. */
  355. protected function returnResponse($content, $responseData = array())
  356. {
  357. if( !$this->packageOptions[ 'responseObject' ] ) {
  358. return $content;
  359. }
  360. $object = new stdClass();
  361. $object->content = $content;
  362. $object->status = $responseData[ 'http_code' ];
  363. if( array_key_exists('errorMessage', $responseData) ) {
  364. $object->error = $responseData[ 'errorMessage' ];
  365. }
  366. return $object;
  367. }
  368. /**
  369. * Convert the curlOptions to an array of usable options for the cURL request
  370. *
  371. * @return array
  372. */
  373. protected function forgeOptions()
  374. {
  375. $results = array();
  376. foreach( $this->curlOptions as $key => $value ) {
  377. $arrayKey = constant( 'CURLOPT_' . $key );
  378. if( !$this->packageOptions[ 'containsFile' ] && $key == 'POSTFIELDS' && is_array( $value ) ) {
  379. $results[ $arrayKey ] = http_build_query( $value, null, '&' );
  380. } else {
  381. $results[ $arrayKey ] = $value;
  382. }
  383. }
  384. return $results;
  385. }
  386. /**
  387. * Append set data to the query string for GET and DELETE cURL requests
  388. *
  389. * @return string
  390. */
  391. protected function appendDataToURL()
  392. {
  393. $parameterString = '';
  394. if( is_array($this->packageOptions[ 'data' ]) && count($this->packageOptions[ 'data' ]) != 0 ) {
  395. $parameterString = '?'. http_build_query( $this->packageOptions[ 'data' ], null, '&' );
  396. }
  397. return $this->curlOptions[ 'URL' ] .= $parameterString;
  398. }
  399. }