Builder.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 an HTTP Authorization header to the request
  232. *
  233. * @param string $token The authorization token that is to be added to the request
  234. * @return Builder
  235. */
  236. public function withAuthorization($token)
  237. {
  238. return $this->withHeader( 'Authorization: ' . $token );
  239. }
  240. /**
  241. * Add a HTTP bearer authorization header to the request
  242. *
  243. * @param string $bearer The bearer token that is to be added to the request
  244. * @return Builder
  245. */
  246. public function withBearer($bearer)
  247. {
  248. return $this->withAuthorization( 'Bearer '. $bearer );
  249. }
  250. /**
  251. * Add a content type HTTP header to the request
  252. *
  253. * @param string $contentType The content type of the file you would like to download
  254. * @return Builder
  255. */
  256. public function withContentType($contentType)
  257. {
  258. return $this->withHeader( 'Content-Type: '. $contentType )
  259. ->withHeader( 'Connection: Keep-Alive' );
  260. }
  261. /**
  262. * Add response headers to the response object or response array
  263. *
  264. * @return Builder
  265. */
  266. public function withResponseHeaders()
  267. {
  268. return $this->withCurlOption( 'HEADER', TRUE );
  269. }
  270. /**
  271. * Return a full response object with HTTP status and headers instead of only the content
  272. *
  273. * @return Builder
  274. */
  275. public function returnResponseObject()
  276. {
  277. return $this->withPackageOption( 'responseObject', true );
  278. }
  279. /**
  280. * Return a full response array with HTTP status and headers instead of only the content
  281. *
  282. * @return Builder
  283. */
  284. public function returnResponseArray()
  285. {
  286. return $this->withPackageOption( 'responseArray', true );
  287. }
  288. /**
  289. * Enable debug mode for the cURL request
  290. *
  291. * @param string $logFile The full path to the log file you want to use
  292. * @return Builder
  293. */
  294. public function enableDebug($logFile)
  295. {
  296. return $this->withPackageOption( 'enableDebug', true )
  297. ->withPackageOption( 'debugFile', $logFile )
  298. ->withOption( 'VERBOSE', true );
  299. }
  300. /**
  301. * Enable Proxy for the cURL request
  302. *
  303. * @param string $proxy Hostname
  304. * @param string $port Port to be used
  305. * @param string $type Scheme to be used by the proxy
  306. * @param string $username Authentication username
  307. * @param string $password Authentication password
  308. * @return Builder
  309. */
  310. public function withProxy($proxy, $port = '', $type = '', $username = '', $password = '')
  311. {
  312. $this->withOption( 'PROXY', $proxy );
  313. if( !empty($port) ) {
  314. $this->withOption( 'PROXYPORT', $port );
  315. }
  316. if( !empty($type) ) {
  317. $this->withOption( 'PROXYTYPE', $type );
  318. }
  319. if( !empty($username) && !empty($password) ) {
  320. $this->withOption( 'PROXYUSERPWD', $username .':'. $password );
  321. }
  322. return $this;
  323. }
  324. /**
  325. * Enable File sending
  326. *
  327. * @return Builder
  328. */
  329. public function containsFile()
  330. {
  331. return $this->withPackageOption( 'containsFile', true );
  332. }
  333. /**
  334. * Add the XDebug session name to the request to allow for easy debugging
  335. *
  336. * @param string $sessionName
  337. * @return Builder
  338. */
  339. public function enableXDebug($sessionName = 'session_1')
  340. {
  341. $this->packageOptions[ 'xDebugSessionName' ] = $sessionName;
  342. return $this;
  343. }
  344. /**
  345. * Send a GET request to a URL using the specified cURL options
  346. *
  347. * @return mixed
  348. */
  349. public function get()
  350. {
  351. $this->appendDataToURL();
  352. return $this->send();
  353. }
  354. /**
  355. * Send a POST request to a URL using the specified cURL options
  356. *
  357. * @return mixed
  358. */
  359. public function post()
  360. {
  361. $this->setPostParameters();
  362. return $this->send();
  363. }
  364. /**
  365. * Send a download request to a URL using the specified cURL options
  366. *
  367. * @param string $fileName
  368. * @return mixed
  369. */
  370. public function download($fileName)
  371. {
  372. $this->appendDataToURL();
  373. $this->packageOptions[ 'saveFile' ] = $fileName;
  374. return $this->send();
  375. }
  376. /**
  377. * Add POST parameters to the curlOptions array
  378. */
  379. protected function setPostParameters()
  380. {
  381. $this->curlOptions[ 'POST' ] = true;
  382. $parameters = $this->packageOptions[ 'data' ];
  383. if( !empty($this->packageOptions[ 'files' ]) ) {
  384. foreach( $this->packageOptions[ 'files' ] as $key => $file ) {
  385. $parameters[ $key ] = $this->getCurlFileValue( $file[ 'fileName' ], $file[ 'mimeType' ], $file[ 'postFileName'] );
  386. }
  387. }
  388. if( $this->packageOptions[ 'asJsonRequest' ] ) {
  389. $parameters = \json_encode($parameters);
  390. }
  391. $this->curlOptions[ 'POSTFIELDS' ] = $parameters;
  392. }
  393. protected function getCurlFileValue($filename, $mimeType, $postFileName)
  394. {
  395. // PHP 5 >= 5.5.0, PHP 7
  396. if( function_exists('curl_file_create') ) {
  397. return curl_file_create($filename, $mimeType, $postFileName);
  398. }
  399. // Use the old style if using an older version of PHP
  400. $value = "@{$filename};filename=" . $postFileName;
  401. if( $mimeType ) {
  402. $value .= ';type=' . $mimeType;
  403. }
  404. return $value;
  405. }
  406. /**
  407. * Send a PUT request to a URL using the specified cURL options
  408. *
  409. * @return mixed
  410. */
  411. public function put()
  412. {
  413. $this->setPostParameters();
  414. return $this->withOption('CUSTOMREQUEST', 'PUT')
  415. ->send();
  416. }
  417. /**
  418. * Send a PATCH request to a URL using the specified cURL options
  419. *
  420. * @return mixed
  421. */
  422. public function patch()
  423. {
  424. $this->setPostParameters();
  425. return $this->withOption('CUSTOMREQUEST', 'PATCH')
  426. ->send();
  427. }
  428. /**
  429. * Send a DELETE request to a URL using the specified cURL options
  430. *
  431. * @return mixed
  432. */
  433. public function delete()
  434. {
  435. $this->setPostParameters();
  436. return $this->withOption('CUSTOMREQUEST', 'DELETE')
  437. ->send();
  438. }
  439. /**
  440. * Send the request
  441. *
  442. * @return mixed
  443. */
  444. protected function send()
  445. {
  446. // Add JSON header if necessary
  447. if( $this->packageOptions[ 'asJsonRequest' ] ) {
  448. $this->withHeader( 'Content-Type: application/json' );
  449. }
  450. if( $this->packageOptions[ 'enableDebug' ] ) {
  451. $debugFile = fopen( $this->packageOptions[ 'debugFile' ], 'w');
  452. $this->withOption('STDERR', $debugFile);
  453. }
  454. // Create the request with all specified options
  455. $this->curlObject = curl_init();
  456. $options = $this->forgeOptions();
  457. curl_setopt_array( $this->curlObject, $options );
  458. // Send the request
  459. $response = curl_exec( $this->curlObject );
  460. $responseHeader = null;
  461. if( $this->curlOptions[ 'HEADER' ] ) {
  462. $headerSize = curl_getinfo( $this->curlObject, CURLINFO_HEADER_SIZE );
  463. $responseHeader = substr( $response, 0, $headerSize );
  464. $response = substr( $response, $headerSize );
  465. }
  466. // Capture additional request information if needed
  467. $responseData = array();
  468. if( $this->packageOptions[ 'responseObject' ] || $this->packageOptions[ 'responseArray' ] ) {
  469. $responseData = curl_getinfo( $this->curlObject );
  470. if( curl_errno($this->curlObject) ) {
  471. $responseData[ 'errorMessage' ] = curl_error($this->curlObject);
  472. }
  473. }
  474. curl_close( $this->curlObject );
  475. if( $this->packageOptions[ 'saveFile' ] ) {
  476. // Save to file if a filename was specified
  477. $file = fopen($this->packageOptions[ 'saveFile' ], 'w');
  478. fwrite($file, $response);
  479. fclose($file);
  480. } else if( $this->packageOptions[ 'asJsonResponse' ] ) {
  481. // Decode the request if necessary
  482. $response = json_decode($response, $this->packageOptions[ 'returnAsArray' ]);
  483. }
  484. if( $this->packageOptions[ 'enableDebug' ] ) {
  485. fclose( $debugFile );
  486. }
  487. // Return the result
  488. return $this->returnResponse( $response, $responseData, $responseHeader );
  489. }
  490. /**
  491. * @param string $headerString Response header string
  492. * @return mixed
  493. */
  494. protected function parseHeaders($headerString)
  495. {
  496. $headers = array_filter(array_map(function ($x) {
  497. $arr = array_map('trim', explode(':', $x, 2));
  498. if( count($arr) == 2 ) {
  499. return [ $arr[ 0 ] => $arr[ 1 ] ];
  500. }
  501. }, array_filter(array_map('trim', explode("\r\n", $headerString)))));
  502. $results = array();
  503. foreach( $headers as $values ) {
  504. if( !is_array($values) ) {
  505. continue;
  506. }
  507. $key = array_keys($values)[ 0 ];
  508. if( isset($results[ $key ]) ) {
  509. $results[ $key ] = array_merge(
  510. (array) $results[ $key ],
  511. array( array_values($values)[ 0 ] )
  512. );
  513. } else {
  514. $results = array_merge(
  515. $results,
  516. $values
  517. );
  518. }
  519. }
  520. return $results;
  521. }
  522. /**
  523. * @param mixed $content Content of the request
  524. * @param array $responseData Additional response information
  525. * @param string $header Response header string
  526. * @return mixed
  527. */
  528. protected function returnResponse($content, array $responseData = array(), $header = null)
  529. {
  530. if( !$this->packageOptions[ 'responseObject' ] && !$this->packageOptions[ 'responseArray' ] ) {
  531. return $content;
  532. }
  533. $object = new stdClass();
  534. $object->content = $content;
  535. $object->status = $responseData[ 'http_code' ];
  536. $object->contentType = $responseData[ 'content_type' ];
  537. if( array_key_exists('errorMessage', $responseData) ) {
  538. $object->error = $responseData[ 'errorMessage' ];
  539. }
  540. if( $this->curlOptions[ 'HEADER' ] ) {
  541. $object->headers = $this->parseHeaders( $header );
  542. }
  543. if( $this->packageOptions[ 'responseObject' ] ) {
  544. return $object;
  545. }
  546. if( $this->packageOptions[ 'responseArray' ] ) {
  547. return (array) $object;
  548. }
  549. return $content;
  550. }
  551. /**
  552. * Convert the curlOptions to an array of usable options for the cURL request
  553. *
  554. * @return array
  555. */
  556. protected function forgeOptions()
  557. {
  558. $results = array();
  559. foreach( $this->curlOptions as $key => $value ) {
  560. $arrayKey = constant( 'CURLOPT_' . $key );
  561. if( !$this->packageOptions[ 'containsFile' ] && $key === 'POSTFIELDS' && is_array( $value ) ) {
  562. $results[ $arrayKey ] = http_build_query( $value, null, '&' );
  563. } else {
  564. $results[ $arrayKey ] = $value;
  565. }
  566. }
  567. if( !empty($this->packageOptions[ 'xDebugSessionName' ]) ) {
  568. $char = strpos($this->curlOptions[ 'URL' ], '?') ? '&' : '?';
  569. $this->curlOptions[ 'URL' ] .= $char . 'XDEBUG_SESSION_START='. $this->packageOptions[ 'xDebugSessionName' ];
  570. }
  571. return $results;
  572. }
  573. /**
  574. * Append set data to the query string for GET and DELETE cURL requests
  575. *
  576. * @return string
  577. */
  578. protected function appendDataToURL()
  579. {
  580. $parameterString = '';
  581. if( is_array($this->packageOptions[ 'data' ]) && count($this->packageOptions[ 'data' ]) != 0 ) {
  582. $parameterString = '?'. http_build_query( $this->packageOptions[ 'data' ], null, '&' );
  583. }
  584. return $this->curlOptions[ 'URL' ] .= $parameterString;
  585. }
  586. }