SetCacheHeaders.php 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Illuminate\Http\Middleware;
  3. use Closure;
  4. class SetCacheHeaders
  5. {
  6. /**
  7. * Add cache related HTTP headers.
  8. *
  9. * @param \Illuminate\Http\Request $request
  10. * @param \Closure $next
  11. * @param string|array $options
  12. * @return \Symfony\Component\HttpFoundation\Response
  13. * @throws \InvalidArgumentException
  14. */
  15. public function handle($request, Closure $next, $options = [])
  16. {
  17. $response = $next($request);
  18. if (! $request->isMethodCacheable() || ! $response->getContent()) {
  19. return $response;
  20. }
  21. if (is_string($options)) {
  22. $options = $this->parseOptions($options);
  23. }
  24. if (isset($options['etag']) && $options['etag'] === true) {
  25. $options['etag'] = md5($response->getContent());
  26. }
  27. $response->setCache($options);
  28. $response->isNotModified($request);
  29. return $response;
  30. }
  31. /**
  32. * Parse the given header options.
  33. *
  34. * @param string $options
  35. * @return array
  36. */
  37. protected function parseOptions($options)
  38. {
  39. return collect(explode(';', $options))->mapWithKeys(function ($option) {
  40. $data = explode('=', $option, 2);
  41. return [$data[0] => $data[1] ?? true];
  42. })->all();
  43. }
  44. }