1 | <?php |
||
14 | class SaveResponse |
||
15 | { |
||
16 | use Utils\FileTrait; |
||
17 | |||
18 | /** |
||
19 | * Execute the middleware. |
||
20 | * |
||
21 | * @param RequestInterface $request |
||
22 | * @param ResponseInterface $response |
||
23 | * @param callable $next |
||
24 | * |
||
25 | * @return ResponseInterface |
||
26 | */ |
||
27 | public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) |
||
28 | { |
||
29 | $response = $next($request, $response); |
||
30 | |||
31 | if ($this->canSave($request, $response)) { |
||
32 | $path = $this->getFilename($request); |
||
33 | |||
34 | //if it's gz compressed, append .gz |
||
35 | if (strtolower($response->getHeaderLine('Content-Encoding')) === 'gzip') { |
||
36 | $path .= '.gz'; |
||
37 | } |
||
38 | |||
39 | self::writeStream($response->getBody(), $path); |
||
40 | } |
||
41 | |||
42 | return $response; |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * Check whether the response can be saved or not. |
||
47 | * |
||
48 | * @param RequestInterface $request |
||
49 | * @param ResponseInterface $response |
||
50 | * |
||
51 | * @return bool |
||
52 | */ |
||
53 | private function canSave(RequestInterface $request, ResponseInterface $response) |
||
54 | { |
||
55 | if ($request->getMethod() !== 'GET') { |
||
56 | return false; |
||
57 | } |
||
58 | |||
59 | if ($response->getStatusCode() !== 200) { |
||
60 | return false; |
||
61 | } |
||
62 | |||
63 | if (!$this->appendQuery && !empty($request->getUri()->getQuery())) { |
||
64 | return false; |
||
65 | } |
||
66 | |||
67 | if ($response->hasHeader('location')) { |
||
68 | return false; |
||
69 | } |
||
70 | |||
71 | $cacheControl = $response->getHeaderLine('Cache-Control'); |
||
72 | |||
73 | if ($cacheControl && (stripos($cacheControl, 'no-cache') !== false || stripos($cacheControl, 'no-store') !== false)) { |
||
74 | return false; |
||
75 | } |
||
76 | |||
77 | return true; |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Write the stream to the given path. |
||
82 | * |
||
83 | * @param StreamInterface $stream |
||
84 | * @param string $path |
||
85 | */ |
||
86 | private static function writeStream(StreamInterface $stream, $path) |
||
108 | } |
||
109 |