FlashMessagesReplacer.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Webkul\FPC\Replacers;
  3. use Spatie\ResponseCache\Replacers\Replacer;
  4. use Symfony\Component\HttpFoundation\Response;
  5. class FlashMessagesReplacer implements Replacer
  6. {
  7. /**
  8. * Replacement string.
  9. */
  10. protected string $replacementString = '\'<bagisto-response-cache-session-flashes>\'';
  11. /**
  12. * Prepare the response to be cached by replacing flash messages with marker.
  13. */
  14. public function prepareResponseToCache(Response $response): void
  15. {
  16. $content = $response->getContent();
  17. // No need to replace existing flash messages since we’re already adding a placeholder by
  18. // checking the response cache enabled flag in the view. At the moment, there is no way
  19. // to make this change directly in the JS component.
  20. $response->setContent($content);
  21. }
  22. /**
  23. * Replace flash messages marker with actual flash messages JSON.
  24. */
  25. public function replaceInCachedResponse(Response $response): void
  26. {
  27. $content = $response->getContent();
  28. if (strpos($content, $this->replacementString) === false) {
  29. return;
  30. }
  31. $flashes = [];
  32. foreach (['success', 'warning', 'error', 'info'] as $type) {
  33. if (session()->has($type)) {
  34. $flashes[] = [
  35. 'type' => $type,
  36. 'message' => session($type),
  37. ];
  38. }
  39. }
  40. $content = str_replace(
  41. $this->replacementString,
  42. collect($flashes)->toJson(),
  43. $content
  44. );
  45. $response->setContent($content);
  46. }
  47. }