SerializeFormatter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * @package Grav\Framework\File\Formatter
  4. *
  5. * @copyright Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Framework\File\Formatter;
  9. class SerializeFormatter implements FormatterInterface
  10. {
  11. /** @var array */
  12. private $config;
  13. /**
  14. * IniFormatter constructor.
  15. * @param array $config
  16. */
  17. public function __construct(array $config = [])
  18. {
  19. $this->config = $config + [
  20. 'file_extension' => '.ser'
  21. ];
  22. }
  23. /**
  24. * @deprecated 1.5 Use $formatter->getDefaultFileExtension() instead.
  25. */
  26. public function getFileExtension()
  27. {
  28. return $this->getDefaultFileExtension();
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function getDefaultFileExtension()
  34. {
  35. $extensions = $this->getSupportedFileExtensions();
  36. return (string) reset($extensions);
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function getSupportedFileExtensions()
  42. {
  43. return (array) $this->config['file_extension'];
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function encode($data)
  49. {
  50. return serialize($this->preserveLines($data, ["\n", "\r"], ['\\n', '\\r']));
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function decode($data)
  56. {
  57. $decoded = @unserialize($data);
  58. if ($decoded === false) {
  59. throw new \RuntimeException('Decoding serialized data failed');
  60. }
  61. return $this->preserveLines($decoded, ['\\n', '\\r'], ["\n", "\r"]);
  62. }
  63. /**
  64. * Preserve new lines, recursive function.
  65. *
  66. * @param mixed $data
  67. * @param array $search
  68. * @param array $replace
  69. * @return mixed
  70. */
  71. protected function preserveLines($data, $search, $replace)
  72. {
  73. if (is_string($data)) {
  74. $data = str_replace($search, $replace, $data);
  75. } elseif (is_array($data)) {
  76. foreach ($data as &$value) {
  77. $value = $this->preserveLines($value, $search, $replace);
  78. }
  79. unset($value);
  80. }
  81. return $data;
  82. }
  83. }