Skip to content

Commit c606193

Browse files
committed
feature: expose deferred response for GT/Fetch
1 parent 0743183 commit c606193

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

composer.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Response.php

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,19 @@ class Response implements ResponseInterface {
3434
/** @var null|callable */
3535
private $exitCallback;
3636
private Deferred $deferred;
37+
private CurlInterface $curl;
3738

3839
public function __construct(
3940
private ?int $statusCode = null,
4041
?ResponseHeaders $headers = null,
4142
private readonly ?Request $request = null,
42-
private readonly ?CurlInterface $curl = null,
43+
?CurlInterface $curl = null,
4344
) {
4445
$this->headers = $headers ?? new ResponseHeaders();
4546
$this->stream = new Stream();
47+
if($curl) {
48+
$this->curl = $curl;
49+
}
4650
}
4751

4852
/** @phpstan-ignore-next-line */
@@ -169,6 +173,42 @@ public function getResponseHeaders():ResponseHeaders {
169173
return $this->headers;
170174
}
171175

176+
public function startDeferredResponse(
177+
CurlInterface $curl
178+
):Deferred {
179+
$this->deferred = new Deferred();
180+
$this->curl = $curl;
181+
return $this->deferred;
182+
}
183+
184+
public function endDeferredResponse(?string $integrity = null):void {
185+
$position = $this->stream->tell();
186+
$this->stream->rewind();
187+
$contents = $this->stream->getContents();
188+
$this->stream->seek($position);
189+
$this->checkIntegrity($integrity, $contents);
190+
$this->deferred->resolve($contents);
191+
}
192+
193+
private function checkIntegrity(?string $integrity, string $contents):void {
194+
if(is_null($integrity)) {
195+
return;
196+
}
197+
198+
[$algo, $hash] = explode("-", $integrity);
199+
200+
$availableAlgos = hash_algos();
201+
if(!in_array($algo, $availableAlgos)) {
202+
throw new InvalidIntegrityAlgorithmException($algo);
203+
}
204+
205+
$hashedContents = hash($algo, $contents);
206+
207+
if($hashedContents !== $hash) {
208+
throw new IntegrityMismatchException();
209+
}
210+
}
211+
172212
/**
173213
* Takes the Response's stream and reads it to completion. Returns a Promise which resolves with the result
174214
* as a Gt\Http\ArrayBuffer.

0 commit comments

Comments
 (0)