|
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
|
7 |
|
private function __construct(ResponseInterface $response, int $expiresAt) |
|
22
|
|
|
{ |
|
23
|
7 |
|
$this->response = $response; |
|
24
|
7 |
|
$this->expiresAt = $expiresAt; |
|
25
|
7 |
|
} |
|
26
|
|
|
|
|
27
|
5 |
|
public function __toString(): string |
|
28
|
|
|
{ |
|
29
|
5 |
|
$contents = $this->response->getBody()->getContents(); |
|
30
|
5 |
|
$stream = new BufferStream(\strlen($contents)); |
|
31
|
5 |
|
$stream->write($contents); |
|
32
|
5 |
|
$this->response = $this->response->withBody($stream); |
|
33
|
|
|
|
|
34
|
5 |
|
return \json_encode([ |
|
35
|
5 |
|
'status_code' => $this->response->getStatusCode(), |
|
36
|
5 |
|
'headers' => $this->response->getHeaders(), |
|
37
|
5 |
|
'body' => $contents, |
|
38
|
5 |
|
'protocol_version' => $this->response->getProtocolVersion(), |
|
39
|
5 |
|
'reason_phrase' => $this->response->getReasonPhrase(), |
|
40
|
5 |
|
'expires_at' => $this->expiresAt, |
|
41
|
|
|
]); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
4 |
|
public static function createFromString(string $json): self |
|
45
|
|
|
{ |
|
46
|
4 |
|
$document = \json_decode($json, true); |
|
47
|
|
|
|
|
48
|
4 |
|
return new self( |
|
49
|
4 |
|
new Response( |
|
50
|
4 |
|
$document['status_code'], |
|
51
|
4 |
|
$document['headers'], |
|
52
|
4 |
|
$document['body'], |
|
53
|
4 |
|
$document['protocol_version'], |
|
54
|
4 |
|
$document['reason_phrase'] |
|
55
|
|
|
), |
|
56
|
4 |
|
$document['expires_at'] |
|
57
|
|
|
); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
5 |
|
public static function createFromResponse(ResponseInterface $response, int $ttl): self |
|
61
|
|
|
{ |
|
62
|
5 |
|
return new self($response, \time() + $ttl); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @return ResponseInterface |
|
67
|
|
|
*/ |
|
68
|
6 |
|
public function getResponse(): ResponseInterface |
|
69
|
|
|
{ |
|
70
|
6 |
|
return $this->response; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* @return bool |
|
75
|
|
|
*/ |
|
76
|
6 |
|
public function hasExpired(): bool |
|
77
|
|
|
{ |
|
78
|
6 |
|
return \time() >= $this->expiresAt; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|