|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Haku\Http; |
| 5 | + |
| 6 | +/* @note Deny direct file access */ |
| 7 | +if (defined('HAKU_ROOT_PATH') === false) exit; |
| 8 | + |
| 9 | +use Haku\Http\Message\Json; |
| 10 | + |
| 11 | +class Fetch |
| 12 | +{ |
| 13 | + private $curl; |
| 14 | + |
| 15 | + protected Headers $headers; |
| 16 | + |
| 17 | + /** |
| 18 | + * Prepares cURL |
| 19 | + */ |
| 20 | + public function __construct( |
| 21 | + protected string $uri, |
| 22 | + protected Method $method = Method::Get, |
| 23 | + array $headers = [] |
| 24 | + ) { |
| 25 | + $this->headers = new Headers($headers); |
| 26 | + |
| 27 | + $this->curl = curl_init($uri); |
| 28 | + |
| 29 | + $this->setOptions([ |
| 30 | + CURLOPT_RETURNTRANSFER => true, |
| 31 | + CURLOPT_HTTPHEADER => $this->headers->getAll(true) |
| 32 | + ]); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Sets a curl option. |
| 37 | + * |
| 38 | + * @see https://www.php.net/manual/en/function.curl-setopt.php |
| 39 | + */ |
| 40 | + public function setOption(int $option, mixed $value): bool |
| 41 | + { |
| 42 | + return curl_setopt($this->curl, $option, $value); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Sets a curl options from array. |
| 47 | + * |
| 48 | + * @see https://www.php.net/manual/en/function.curl-setopt-array.php |
| 49 | + */ |
| 50 | + public function setOptions(array $options): bool |
| 51 | + { |
| 52 | + return curl_setopt_array($this->curl, $options); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Makes a JSON request |
| 57 | + */ |
| 58 | + public function json(Json $payload = null): object |
| 59 | + { |
| 60 | + if (!$this->headers->has('Accept')) |
| 61 | + { |
| 62 | + $this->headers->set('Accept', 'application/json'); |
| 63 | + } |
| 64 | + |
| 65 | + $this->headers->set('Content-Type', 'application/json'); |
| 66 | + |
| 67 | + if ($this->method === Method::Post && $payload !== null) |
| 68 | + { |
| 69 | + curl_setopt($this->curl, CURLOPT_POSTFIELDS, $payload->asRendered()); |
| 70 | + } |
| 71 | + |
| 72 | + $response = curl_exec($this->curl); |
| 73 | + |
| 74 | + curl_close($this->curl); |
| 75 | + |
| 76 | + if (!json_validate($response)) |
| 77 | + { |
| 78 | + throw new Exceptions\HttpException('Invalid JSON response.'); |
| 79 | + } |
| 80 | + |
| 81 | + return json_decode($response); |
| 82 | + } |
| 83 | + |
| 84 | + public function close() |
| 85 | + { |
| 86 | + curl_close($this->curl); |
| 87 | + } |
| 88 | + |
| 89 | +} |
0 commit comments