| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php
- require('response.php');
- class fetch {
- private bool $has_content;
- private string $method;
- private ?string $received;
- private CurlHandle $request;
- public function __construct(string $url, string $method = 'GET') {
- $this->received = null;
- $this->has_content = false;
- $this->method = $method;
- $this->request = curl_init();
- $this->setopt(CURLOPT_RETURNTRANSFER, true);
- $this->setopt(CURLOPT_FAILONERROR, true);
- $this->setopt(CURLOPT_HEADER, true);
- $this->setopt(CURLOPT_CUSTOMREQUEST, $method);
- $this->setopt(CURLOPT_URL, curl_escape($url));
- }
- public function set_json(array $content): object {
- if ($this->has_content) {
- throw new RuntimeException('JSON content already set.');
- }
- if ($this->method === 'GET' or $this->method === 'HEAD') {
- throw new TypeError("JSON request can not be GET or HEAD.");
- }
- $converted = json_encode($content);
- $headers = [ 'Content-Type: application/json' ];
-
- $this->has_content = true;
- $this->setopt(CURLOPT_POSTFIELDS, $converted);
- $this->setopt(CURLOPT_HTTPHEADER, $headers);
- return $this;
- }
- public function request(): string {
- if ($this->received !== null) {
- return $this->received;
- }
- $result = curl_exec($this->request);
- $error = curl_error($this->request);
- $error_number = curl_errno($this->request);
-
- curl_close($this->received);
-
- if ($result !== false and $error_number === 0) {
- return $this->received = $result;
- }
- throw new RuntimeException(
- 'Can not fetch request. Error code '
- .string($error_number)
- .': "'.$error.'".'
- );
- }
- private function setopt(int $option, mixed $content): void {
- curl_setopt($this->request, $option, $content);
- }
- }
|