1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Middleware\Cache; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use RingCentral\Psr7\BufferStream; |
7
|
|
|
use RingCentral\Psr7\Response; |
8
|
|
|
|
9
|
|
|
final class Document |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var ResponseInterface |
13
|
|
|
*/ |
14
|
|
|
private $response; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var int |
18
|
|
|
*/ |
19
|
|
|
private $expiresAt; |
20
|
|
|
|
21
|
|
|
public static function createFromString(string $json): self |
22
|
|
|
{ |
23
|
|
|
$document = json_decode($json, true); |
24
|
|
|
return new self( |
25
|
|
|
new Response( |
26
|
|
|
$document['status_code'], |
27
|
|
|
$document['headers'], |
28
|
|
|
$document['body'], |
29
|
|
|
$document['protocol_version'], |
30
|
|
|
$document['reason_phrase'] |
31
|
|
|
), |
32
|
|
|
$document['expires_at'] |
33
|
|
|
); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public static function createFromResponse(ResponseInterface $response, int $ttl): self |
37
|
|
|
{ |
38
|
|
|
return new self($response, time() + $ttl); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private function __construct(ResponseInterface $response, int $expiresAt) |
42
|
|
|
{ |
43
|
|
|
$this->response = $response; |
44
|
|
|
$this->expiresAt = $expiresAt; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @return ResponseInterface |
49
|
|
|
*/ |
50
|
|
|
public function getResponse(): ResponseInterface |
51
|
|
|
{ |
52
|
|
|
return $this->response; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @return bool |
57
|
|
|
*/ |
58
|
|
|
public function hasExpired(): bool |
59
|
|
|
{ |
60
|
|
|
return time() >= $this->expiresAt; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function __toString(): string |
64
|
|
|
{ |
65
|
|
|
$contents = $this->response->getBody()->getContents(); |
66
|
|
|
$stream = new BufferStream(strlen($contents)); |
67
|
|
|
$stream->write($contents); |
68
|
|
|
$this->response = $this->response->withBody($stream); |
69
|
|
|
return json_encode([ |
70
|
|
|
'status_code' => $this->response->getStatusCode(), |
71
|
|
|
'headers' => $this->response->getHeaders(), |
72
|
|
|
'body' => $contents, |
73
|
|
|
'protocol_version' => $this->response->getProtocolVersion(), |
74
|
|
|
'reason_phrase' => $this->response->getReasonPhrase(), |
75
|
|
|
'expires_at' => $this->expiresAt, |
76
|
|
|
]); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|