-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerializableResponse.php
70 lines (59 loc) · 1.93 KB
/
SerializableResponse.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php declare(strict_types=1);
namespace StrictPhp\HttpClients\Responses;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\ResponseInterface;
use Serializable;
use StrictPhp\HttpClients\Helpers\Stream;
use Stringable;
/**
* @phpstan-type SerializeType array{class: class-string<ResponseInterface>, protocolVersion: string,
* headers: array<string>|array<string, array<string>>, code: int, reason: string, body: string}
*/
final class SerializableResponse implements Serializable, Stringable
{
public function __construct(
public readonly ResponseInterface $response,
) {
}
public function __toString(): string
{
return (string) $this->serialize();
}
/**
* @param SerializeType $data
*/
public function __unserialize(array $data): void
{
$response = new ($data['class']);
foreach ($data['headers'] as $name => $value) {
$response = $response->withHeader($name, $value);
}
$this->response = $response->withStatus($data['code'], $data['reason'])
->withProtocolVersion($data['protocolVersion'])
->withBody(Utils::streamFor($data['body']));
}
/**
* @return SerializeType
*/
public function __serialize(): array
{
return [
'class' => $this->response::class,
'protocolVersion' => $this->response->getProtocolVersion(),
'headers' => $this->response->getHeaders(),
'code' => $this->response->getStatusCode(),
'reason' => $this->response->getReasonPhrase(),
'body' => Stream::content($this->response->getBody()),
];
}
public function unserialize(string $data): void
{
/** @var SerializeType $responseData */
$responseData = unserialize($data);
$this->__unserialize($responseData);
}
public function serialize(): ?string
{
return serialize($this->__serialize());
}
}