fetch.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. require('response.php');
  3. class fetch {
  4. private bool $has_content;
  5. private string $method;
  6. private ?string $received;
  7. private CurlHandle $request;
  8. public function __construct(string $url, string $method = 'GET') {
  9. $this->received = null;
  10. $this->has_content = false;
  11. $this->method = $method;
  12. $this->request = curl_init();
  13. $this->setopt(CURLOPT_RETURNTRANSFER, true);
  14. $this->setopt(CURLOPT_FAILONERROR, true);
  15. $this->setopt(CURLOPT_HEADER, true);
  16. $this->setopt(CURLOPT_CUSTOMREQUEST, $method);
  17. $this->setopt(CURLOPT_URL, curl_escape($url));
  18. }
  19. public function set_json(array $content): object {
  20. if ($this->has_content) {
  21. throw new RuntimeException('JSON content already set.');
  22. }
  23. if ($this->method === 'GET' or $this->method === 'HEAD') {
  24. throw new TypeError("JSON request can not be GET or HEAD.");
  25. }
  26. $converted = json_encode($content);
  27. $headers = [ 'Content-Type: application/json' ];
  28. $this->has_content = true;
  29. $this->setopt(CURLOPT_POSTFIELDS, $converted);
  30. $this->setopt(CURLOPT_HTTPHEADER, $headers);
  31. return $this;
  32. }
  33. public function request(): string {
  34. if ($this->received !== null) {
  35. return $this->received;
  36. }
  37. $result = curl_exec($this->request);
  38. $error = curl_error($this->request);
  39. $error_number = curl_errno($this->request);
  40. curl_close($this->received);
  41. if ($result !== false and $error_number === 0) {
  42. return $this->received = $result;
  43. }
  44. throw new RuntimeException(
  45. 'Can not fetch request. Error code '
  46. .string($error_number)
  47. .': "'.$error.'".'
  48. );
  49. }
  50. private function setopt(int $option, mixed $content): void {
  51. curl_setopt($this->request, $option, $content);
  52. }
  53. }