PageCachePlugin.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /***
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\PageCache\Model\App;
  7. class PageCachePlugin
  8. {
  9. /**
  10. * Label for compressed cache entries
  11. */
  12. const COMPRESSION_PREFIX = 'COMPRESSED_CACHE_';
  13. /**
  14. * Enable type management by adding type tag, and enable cache compression
  15. *
  16. * @param \Magento\Framework\App\PageCache\Cache $subject
  17. * @param string $data
  18. * @param string $identifier
  19. * @param string[] $tags
  20. * @param int|null $lifeTime
  21. * @return array
  22. *
  23. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  24. */
  25. public function beforeSave(
  26. \Magento\Framework\App\PageCache\Cache $subject,
  27. $data,
  28. $identifier,
  29. $tags = [],
  30. $lifeTime = null
  31. ) {
  32. $data = $this->handleCompression($data);
  33. $tags[] = \Magento\PageCache\Model\Cache\Type::CACHE_TAG;
  34. return [$data, $identifier, $tags, $lifeTime];
  35. }
  36. /**
  37. * Enable cache de-compression
  38. *
  39. * @param \Magento\Framework\App\PageCache\Cache $subject
  40. * @param string $result
  41. * @return string|bool
  42. * @throws \Magento\Framework\Exception\LocalizedException
  43. *
  44. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  45. */
  46. public function afterLoad(
  47. \Magento\Framework\App\PageCache\Cache $subject,
  48. $result
  49. ) {
  50. if ($result && strpos($result, self::COMPRESSION_PREFIX) === 0) {
  51. $result = function_exists('gzuncompress')
  52. ? gzuncompress(substr($result, strlen(self::COMPRESSION_PREFIX)))
  53. : false;
  54. }
  55. return $result;
  56. }
  57. /**
  58. * Label compressed entries and check if gzcompress exists
  59. *
  60. * @param string $data
  61. * @return string
  62. */
  63. private function handleCompression($data)
  64. {
  65. if (function_exists('gzcompress')) {
  66. $data = self::COMPRESSION_PREFIX . gzcompress($data);
  67. }
  68. return $data;
  69. }
  70. }