1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ResponseCache; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\Response; |
6
|
|
|
use Symfony\Component\HttpFoundation\BinaryFileResponse; |
7
|
|
|
|
8
|
|
|
class ResponseSerializer |
9
|
|
|
{ |
10
|
|
|
const RESPONSE_TYPE_NORMAL = 1; |
11
|
|
|
const RESPONSE_TYPE_FILE = 2; |
12
|
|
|
|
13
|
|
|
public function serialize(Response $response): string |
14
|
|
|
{ |
15
|
|
|
return serialize($this->getResponseData($response)); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function unserialize(string $serializedResponse): Response |
19
|
|
|
{ |
20
|
|
|
$responseProperties = unserialize($serializedResponse); |
21
|
|
|
|
22
|
|
|
$response = $this->buildResponse($responseProperties); |
23
|
|
|
|
24
|
|
|
$response->headers = $responseProperties['headers']; |
25
|
|
|
|
26
|
|
|
return $response; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
private function getResponseData(Response $response): array |
30
|
|
|
{ |
31
|
|
|
$type = self::RESPONSE_TYPE_NORMAL; |
32
|
|
|
$statusCode = $response->getStatusCode(); |
33
|
|
|
$headers = $response->headers; |
34
|
|
|
|
35
|
|
|
if ($response instanceof BinaryFileResponse) { |
36
|
|
|
$content = $response->getFile()->getPathname(); |
37
|
|
|
$type = self::RESPONSE_TYPE_FILE; |
38
|
|
|
|
39
|
|
|
return compact('content', 'statusCode', 'headers', 'type'); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$content = $response->getContent(); |
43
|
|
|
|
44
|
|
|
return compact('content', 'statusCode', 'headers', 'type'); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function buildResponse(array $responseProperties): Response |
48
|
|
|
{ |
49
|
|
|
$type = $responseProperties['type'] ?? self::RESPONSE_TYPE_NORMAL; |
50
|
|
|
|
51
|
|
|
if ($type === self::RESPONSE_TYPE_FILE) { |
52
|
|
|
return new BinaryFileResponse($responseProperties['content'], $responseProperties['statusCode']); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return new Response($responseProperties['content'], $responseProperties['statusCode']); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|