1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ResponseCache; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\Response; |
6
|
|
|
use Spatie\ResponseCache\Exceptions\CouldNotUnserialize; |
7
|
|
|
use Symfony\Component\HttpFoundation\BinaryFileResponse; |
8
|
|
|
|
9
|
|
|
class ResponseSerializer |
10
|
|
|
{ |
11
|
|
|
const RESPONSE_TYPE_NORMAL = 'response_type_normal'; |
12
|
|
|
const RESPONSE_TYPE_FILE = 'response_type_file'; |
13
|
|
|
|
14
|
|
|
public function serialize(Response $response): string |
15
|
|
|
{ |
16
|
|
|
return serialize($this->getResponseData($response)); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function unserialize(string $serializedResponse): Response |
20
|
|
|
{ |
21
|
|
|
$responseProperties = unserialize($serializedResponse); |
22
|
|
|
|
23
|
|
|
if (! $this->containsValidResponseProperties($responseProperties)) { |
24
|
|
|
throw CouldNotUnserialize::serializedResponse($serializedResponse); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
$response = $this->buildResponse($responseProperties); |
28
|
|
|
|
29
|
|
|
$response->headers = $responseProperties['headers']; |
30
|
|
|
|
31
|
|
|
return $response; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
protected function getResponseData(Response $response): array |
35
|
|
|
{ |
36
|
|
|
$statusCode = $response->getStatusCode(); |
37
|
|
|
$headers = $response->headers; |
38
|
|
|
|
39
|
|
|
if ($response instanceof BinaryFileResponse) { |
40
|
|
|
$content = $response->getFile()->getPathname(); |
41
|
|
|
$type = self::RESPONSE_TYPE_FILE; |
42
|
|
|
|
43
|
|
|
return compact('statusCode', 'headers', 'content', 'type'); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$content = $response->getContent(); |
47
|
|
|
$type = self::RESPONSE_TYPE_NORMAL; |
48
|
|
|
|
49
|
|
|
return compact('statusCode', 'headers', 'content', 'type'); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected function containsValidResponseProperties($properties): bool |
53
|
|
|
{ |
54
|
|
|
if (! is_array($properties)) { |
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if (! isset($properties['content'], $properties['statusCode'])) { |
59
|
|
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return true; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
protected function buildResponse(array $responseProperties): Response |
66
|
|
|
{ |
67
|
|
|
$type = $responseProperties['type'] ?? self::RESPONSE_TYPE_NORMAL; |
68
|
|
|
|
69
|
|
|
if ($type === self::RESPONSE_TYPE_FILE) { |
70
|
|
|
return new BinaryFileResponse( |
71
|
|
|
$responseProperties['content'], |
72
|
|
|
$responseProperties['statusCode'] |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return new Response($responseProperties['content'], $responseProperties['statusCode']); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|