Builder.php 18 KB

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