Builder.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. 'SSL_VERIFYPEER' => false,
  18. 'HEADER' => false,
  19. );
  20. /** @var array $packageOptions Array with options that are not specific to cURL but are used by the package */
  21. protected $packageOptions = array(
  22. 'data' => array(),
  23. 'files' => array(),
  24. 'asJsonRequest' => false,
  25. 'asJsonResponse' => false,
  26. 'returnAsArray' => false,
  27. 'responseObject' => false,
  28. 'responseArray' => false,
  29. 'enableDebug' => false,
  30. 'xDebugSessionName' => '',
  31. 'containsFile' => false,
  32. 'debugFile' => '',
  33. 'saveFile' => '',
  34. );
  35. /**
  36. * Set the URL to which the request is to be sent
  37. *
  38. * @param $url string The URL to which the request is to be sent
  39. * @return Builder
  40. */
  41. public function to($url)
  42. {
  43. return $this->withCurlOption( 'URL', $url );
  44. }
  45. /**
  46. * Set the request timeout
  47. *
  48. * @param float $timeout The timeout for the request (in seconds, fractions of a second are okay. Default: 30 seconds)
  49. * @return Builder
  50. */
  51. public function withTimeout($timeout = 30.0)
  52. {
  53. return $this->withCurlOption( 'TIMEOUT_MS', ($timeout * 1000) );
  54. }
  55. /**
  56. * Add GET or POST data to the request
  57. *
  58. * @param mixed $data Array of data that is to be sent along with the request
  59. * @return Builder
  60. */
  61. public function withData($data = array())
  62. {
  63. return $this->withPackageOption( 'data', $data );
  64. }
  65. /**
  66. * Add a file to the request
  67. *
  68. * @param string $key Identifier of the file (how it will be referenced by the server in the $_FILES array)
  69. * @param string $path Full path to the file you want to send
  70. * @param string $mimeType Mime type of the file
  71. * @param string $postFileName Name of the file when sent. Defaults to file name
  72. *
  73. * @return Builder
  74. */
  75. public function withFile($key, $path, $mimeType = '', $postFileName = '')
  76. {
  77. $fileData = array(
  78. 'fileName' => $path,
  79. 'mimeType' => $mimeType,
  80. 'postFileName' => $postFileName,
  81. );
  82. $this->packageOptions[ 'files' ][ $key ] = $fileData;
  83. return $this->containsFile();
  84. }
  85. /**
  86. * Allow for redirects in the request
  87. *
  88. * @return Builder
  89. */
  90. public function allowRedirect()
  91. {
  92. return $this->withCurlOption( 'FOLLOWLOCATION', true );
  93. }
  94. /**
  95. * Configure the package to encode and decode the request data
  96. *
  97. * @param boolean $asArray Indicates whether or not the data should be returned as an array. Default: false
  98. * @return Builder
  99. */
  100. public function asJson($asArray = false)
  101. {
  102. return $this->asJsonRequest()
  103. ->asJsonResponse( $asArray );
  104. }
  105. /**
  106. * Configure the package to encode the request data to json before sending it to the server
  107. *
  108. * @return Builder
  109. */
  110. public function asJsonRequest()
  111. {
  112. return $this->withPackageOption( 'asJsonRequest', true );
  113. }
  114. /**
  115. * Configure the package to decode the request data from json to object or associative array
  116. *
  117. * @param boolean $asArray Indicates whether or not the data should be returned as an array. Default: false
  118. * @return Builder
  119. */
  120. public function asJsonResponse($asArray = false)
  121. {
  122. return $this->withPackageOption( 'asJsonResponse', true )
  123. ->withPackageOption( 'returnAsArray', $asArray );
  124. }
  125. // /**
  126. // * Send the request over a secure connection
  127. // *
  128. // * @return Builder
  129. // */
  130. // public function secure()
  131. // {
  132. // return $this;
  133. // }
  134. /**
  135. * Set any specific cURL option
  136. *
  137. * @param string $key The name of the cURL option
  138. * @param mixed $value The value to which the option is to be set
  139. * @return Builder
  140. */
  141. public function withOption($key, $value)
  142. {
  143. return $this->withCurlOption( $key, $value );
  144. }
  145. /**
  146. * Set Cookie File
  147. *
  148. * @param string $cookieFile File name to read cookies from
  149. * @return Builder
  150. */
  151. public function setCookieFile($cookieFile)
  152. {
  153. return $this->withOption( 'COOKIEFILE', $cookieFile );
  154. }
  155. /**
  156. * Set Cookie Jar
  157. *
  158. * @param string $cookieJar File name to store cookies to
  159. * @return Builder
  160. */
  161. public function setCookieJar($cookieJar)
  162. {
  163. return $this->withOption( 'COOKIEJAR', $cookieJar );
  164. }
  165. /**
  166. * Set any specific cURL option
  167. *
  168. * @param string $key The name of the cURL option
  169. * @param string $value The value to which the option is to be set
  170. * @return Builder
  171. */
  172. protected function withCurlOption($key, $value)
  173. {
  174. $this->curlOptions[ $key ] = $value;
  175. return $this;
  176. }
  177. /**
  178. * Set any specific package option
  179. *
  180. * @param string $key The name of the cURL option
  181. * @param string $value The value to which the option is to be set
  182. * @return Builder
  183. */
  184. protected function withPackageOption($key, $value)
  185. {
  186. $this->packageOptions[ $key ] = $value;
  187. return $this;
  188. }
  189. /**
  190. * Add a HTTP header to the request
  191. *
  192. * @param string $header The HTTP header that is to be added to the request
  193. * @return Builder
  194. */
  195. public function withHeader($header)
  196. {
  197. $this->curlOptions[ 'HTTPHEADER' ][] = $header;
  198. return $this;
  199. }
  200. /**
  201. * Add multiple HTTP header at the same time to the request
  202. *
  203. * @param array $headers Array of HTTP headers that must be added to the request
  204. * @return Builder
  205. */
  206. public function withHeaders(array $headers)
  207. {
  208. $this->curlOptions[ 'HTTPHEADER' ] = array_merge(
  209. $this->curlOptions[ 'HTTPHEADER' ], $headers
  210. );
  211. return $this;
  212. }
  213. /**
  214. * Add a content type HTTP header to the request
  215. *
  216. * @param string $contentType The content type of the file you would like to download
  217. * @return Builder
  218. */
  219. public function withContentType($contentType)
  220. {
  221. return $this->withHeader( 'Content-Type: '. $contentType )
  222. ->withHeader( 'Connection: Keep-Alive' );
  223. }
  224. /**
  225. * Add response headers to the response object or response array
  226. *
  227. * @return Builder
  228. */
  229. public function withResponseHeaders()
  230. {
  231. return $this->withCurlOption( 'HEADER', TRUE );
  232. }
  233. /**
  234. * Return a full response object with HTTP status and headers instead of only the content
  235. *
  236. * @return Builder
  237. */
  238. public function returnResponseObject()
  239. {
  240. return $this->withPackageOption( 'responseObject', true );
  241. }
  242. /**
  243. * Return a full response array with HTTP status and headers instead of only the content
  244. *
  245. * @return Builder
  246. */
  247. public function returnResponseArray()
  248. {
  249. return $this->withPackageOption( 'responseArray', true );
  250. }
  251. /**
  252. * Enable debug mode for the cURL request
  253. *
  254. * @param string $logFile The full path to the log file you want to use
  255. * @return Builder
  256. */
  257. public function enableDebug($logFile)
  258. {
  259. return $this->withPackageOption( 'enableDebug', true )
  260. ->withPackageOption( 'debugFile', $logFile )
  261. ->withOption( 'VERBOSE', true );
  262. }
  263. /**
  264. * Enable Proxy for the cURL request
  265. *
  266. * @param string $proxy Hostname
  267. * @param string $port Port to be used
  268. * @param string $type Scheme to be used by the proxy
  269. * @param string $username Authentication username
  270. * @param string $password Authentication password
  271. * @return Builder
  272. */
  273. public function withProxy($proxy, $port = '', $type = '', $username = '', $password = '')
  274. {
  275. $this->withOption( 'PROXY', $proxy );
  276. if( !empty($port) ) {
  277. $this->withOption( 'PROXYPORT', $port );
  278. }
  279. if( !empty($type) ) {
  280. $this->withOption( 'PROXYTYPE', $type );
  281. }
  282. if( !empty($username) && !empty($password) ) {
  283. $this->withOption( 'PROXYUSERPWD', $username .':'. $password );
  284. }
  285. return $this;
  286. }
  287. /**
  288. * Enable File sending
  289. *
  290. * @return Builder
  291. */
  292. public function containsFile()
  293. {
  294. return $this->withPackageOption( 'containsFile', true );
  295. }
  296. /**
  297. * Add the XDebug session name to the request to allow for easy debugging
  298. *
  299. * @param string $sessionName
  300. * @return Builder
  301. */
  302. public function enableXDebug($sessionName = 'session_1')
  303. {
  304. $this->packageOptions[ 'xDebugSessionName' ] = $sessionName;
  305. return $this;
  306. }
  307. /**
  308. * Send a GET request to a URL using the specified cURL options
  309. *
  310. * @return mixed
  311. */
  312. public function get()
  313. {
  314. $this->appendDataToURL();
  315. return $this->send();
  316. }
  317. /**
  318. * Send a POST request to a URL using the specified cURL options
  319. *
  320. * @return mixed
  321. */
  322. public function post()
  323. {
  324. $this->setPostParameters();
  325. return $this->send();
  326. }
  327. /**
  328. * Send a download request to a URL using the specified cURL options
  329. *
  330. * @param string $fileName
  331. * @return mixed
  332. */
  333. public function download($fileName)
  334. {
  335. $this->packageOptions[ 'saveFile' ] = $fileName;
  336. return $this->send();
  337. }
  338. /**
  339. * Add POST parameters to the curlOptions array
  340. */
  341. protected function setPostParameters()
  342. {
  343. $this->curlOptions[ 'POST' ] = true;
  344. $parameters = $this->packageOptions[ 'data' ];
  345. if( !empty($this->packageOptions[ 'files' ]) ) {
  346. foreach( $this->packageOptions[ 'files' ] as $key => $file ) {
  347. $parameters[ $key ] = $this->getCurlFileValue( $file[ 'fileName' ], $file[ 'mimeType' ], $file[ 'postFileName'] );
  348. }
  349. }
  350. if( $this->packageOptions[ 'asJsonRequest' ] ) {
  351. $parameters = json_encode($parameters);
  352. }
  353. $this->curlOptions[ 'POSTFIELDS' ] = $parameters;
  354. }
  355. protected function getCurlFileValue($filename, $mimeType, $postFileName)
  356. {
  357. // PHP 5 >= 5.5.0, PHP 7
  358. if( function_exists('curl_file_create') ) {
  359. return curl_file_create($filename, $mimeType, $postFileName);
  360. }
  361. // Use the old style if using an older version of PHP
  362. $value = "@{$filename};filename=" . $postFileName;
  363. if( $mimeType ) {
  364. $value .= ';type=' . $mimeType;
  365. }
  366. return $value;
  367. }
  368. /**
  369. * Send a PUT request to a URL using the specified cURL options
  370. *
  371. * @return mixed
  372. */
  373. public function put()
  374. {
  375. $this->setPostParameters();
  376. return $this->withOption('CUSTOMREQUEST', 'PUT')
  377. ->send();
  378. }
  379. /**
  380. * Send a PATCH request to a URL using the specified cURL options
  381. *
  382. * @return mixed
  383. */
  384. public function patch()
  385. {
  386. $this->setPostParameters();
  387. return $this->withOption('CUSTOMREQUEST', 'PATCH')
  388. ->send();
  389. }
  390. /**
  391. * Send a DELETE request to a URL using the specified cURL options
  392. *
  393. * @return mixed
  394. */
  395. public function delete()
  396. {
  397. $this->appendDataToURL();
  398. return $this->withOption('CUSTOMREQUEST', 'DELETE')
  399. ->send();
  400. }
  401. /**
  402. * Send the request
  403. *
  404. * @return mixed
  405. */
  406. protected function send()
  407. {
  408. // Add JSON header if necessary
  409. if( $this->packageOptions[ 'asJsonRequest' ] ) {
  410. $this->withHeader( 'Content-Type: application/json' );
  411. }
  412. if( $this->packageOptions[ 'enableDebug' ] ) {
  413. $debugFile = fopen( $this->packageOptions[ 'debugFile' ], 'w');
  414. $this->withOption('STDERR', $debugFile);
  415. }
  416. // Create the request with all specified options
  417. $this->curlObject = curl_init();
  418. $options = $this->forgeOptions();
  419. curl_setopt_array( $this->curlObject, $options );
  420. // Send the request
  421. $response = curl_exec( $this->curlObject );
  422. $responseHeader = null;
  423. if( $this->curlOptions[ 'HEADER' ] ) {
  424. $headerSize = curl_getinfo( $this->curlObject, CURLINFO_HEADER_SIZE );
  425. $responseHeader = substr( $response, 0, $headerSize );
  426. $response = substr( $response, $headerSize );
  427. }
  428. // Capture additional request information if needed
  429. $responseData = array();
  430. if( $this->packageOptions[ 'responseObject' ] || $this->packageOptions[ 'responseArray' ] ) {
  431. $responseData = curl_getinfo( $this->curlObject );
  432. if( curl_errno($this->curlObject) ) {
  433. $responseData[ 'errorMessage' ] = curl_error($this->curlObject);
  434. }
  435. }
  436. curl_close( $this->curlObject );
  437. if( $this->packageOptions[ 'saveFile' ] ) {
  438. // Save to file if a filename was specified
  439. $file = fopen($this->packageOptions[ 'saveFile' ], 'w');
  440. fwrite($file, $response);
  441. fclose($file);
  442. } else if( $this->packageOptions[ 'asJsonResponse' ] ) {
  443. // Decode the request if necessary
  444. $response = json_decode($response, $this->packageOptions[ 'returnAsArray' ]);
  445. }
  446. if( $this->packageOptions[ 'enableDebug' ] ) {
  447. fclose( $debugFile );
  448. }
  449. // Return the result
  450. return $this->returnResponse( $response, $responseData, $responseHeader );
  451. }
  452. /**
  453. * @param string $headerString Response header string
  454. * @return mixed
  455. */
  456. protected function parseHeaders($headerString)
  457. {
  458. $headers = array_filter(array_map(function ($x) {
  459. $arr = array_map('trim', explode(':', $x, 2));
  460. if( count($arr) == 2 ) {
  461. return [ $arr[ 0 ] => $arr[ 1 ] ];
  462. }
  463. }, array_filter(array_map('trim', explode("\r\n", $headerString)))));
  464. $return = [];
  465. foreach($headers as $val){
  466. $key = array_keys($val)[0];
  467. if(isset($return[$key])){
  468. $return[$key] = array_merge((array) $return[$key], [array_values($val)[0]]);
  469. }else{
  470. $return = array_merge($return, $val);
  471. }
  472. }
  473. return $return;
  474. }
  475. /**
  476. * @param mixed $content Content of the request
  477. * @param array $responseData Additional response information
  478. * @param string $header Response header string
  479. * @return mixed
  480. */
  481. protected function returnResponse($content, array $responseData = array(), $header = null)
  482. {
  483. if( !$this->packageOptions[ 'responseObject' ] && !$this->packageOptions[ 'responseArray' ] ) {
  484. return $content;
  485. }
  486. $object = new stdClass();
  487. $object->content = $content;
  488. $object->status = $responseData[ 'http_code' ];
  489. $object->contentType = $responseData[ 'content_type' ];
  490. if( array_key_exists('errorMessage', $responseData) ) {
  491. $object->error = $responseData[ 'errorMessage' ];
  492. }
  493. if( $this->curlOptions[ 'HEADER' ] ) {
  494. $object->headers = $this->parseHeaders( $header );
  495. }
  496. if( $this->packageOptions[ 'responseObject' ] ) {
  497. return $object;
  498. }
  499. if( $this->packageOptions[ 'responseArray' ] ) {
  500. return (array) $object;
  501. }
  502. return $content;
  503. }
  504. /**
  505. * Convert the curlOptions to an array of usable options for the cURL request
  506. *
  507. * @return array
  508. */
  509. protected function forgeOptions()
  510. {
  511. $results = array();
  512. foreach( $this->curlOptions as $key => $value ) {
  513. $arrayKey = constant( 'CURLOPT_' . $key );
  514. if( !$this->packageOptions[ 'containsFile' ] && $key == 'POSTFIELDS' && is_array( $value ) ) {
  515. $results[ $arrayKey ] = http_build_query( $value, null, '&' );
  516. } else {
  517. $results[ $arrayKey ] = $value;
  518. }
  519. }
  520. if( !empty($this->packageOptions[ 'xDebugSessionName' ]) ) {
  521. $char = strpos($this->curlOptions[ 'URL' ], '?') ? '&' : '?';
  522. $this->curlOptions[ 'URL' ] .= $char . 'XDEBUG_SESSION_START='. $this->packageOptions[ 'xDebugSessionName' ];
  523. }
  524. return $results;
  525. }
  526. /**
  527. * Append set data to the query string for GET and DELETE cURL requests
  528. *
  529. * @return string
  530. */
  531. protected function appendDataToURL()
  532. {
  533. $parameterString = '';
  534. if( is_array($this->packageOptions[ 'data' ]) && count($this->packageOptions[ 'data' ]) != 0 ) {
  535. $parameterString = '?'. http_build_query( $this->packageOptions[ 'data' ], null, '&' );
  536. }
  537. return $this->curlOptions[ 'URL' ] .= $parameterString;
  538. }
  539. }