GzipEncoding.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace KarmaFW\App\Middlewares;
  3. use \KarmaFW\Http\Request;
  4. use \KarmaFW\Http\Response;
  5. class GzipEncoding
  6. {
  7. public function __invoke(Request $request, Response $response, callable $next)
  8. {
  9. $response = $next($request, $response);
  10. $content_type = $response->getContentType();
  11. $content_type_short = explode(';', $content_type)[0];
  12. $contents_types = [
  13. 'text/html',
  14. 'text/plain',
  15. 'text/xml',
  16. 'text/css',
  17. 'application/x-javascript',
  18. 'application/javascript',
  19. 'application/ecmascript',
  20. 'application/json',
  21. 'application/xml',
  22. 'image/svg+xml',
  23. ];
  24. if (empty($content_types) || ! in_array($content_type_short, $content_types)) {
  25. return $response;
  26. }
  27. $content_length = $response->getContentLength();
  28. if ($content_length > 1000) {
  29. $content_minimified = (string) gzencode($response->getBody());
  30. $response->setBody($content_minimified);
  31. $content_minimified_length = $response->getContentLength();
  32. $response->addHeader('Content-Encoding', 'gzip');
  33. $response->addHeader('X-Encoding', 'gzip');
  34. // add information headers
  35. $response->addHeader('X-Before-Encoding-Content-Length', $content_length);
  36. $response->addHeader('X-After-Encoding-Content-Length', $content_minimified_length);
  37. }
  38. return $response;
  39. }
  40. }