SerializeFormatter.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\File\Formatter
  5. *
  6. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Grav\Framework\File\Formatter;
  10. use Grav\Framework\File\Interfaces\FileFormatterInterface;
  11. class SerializeFormatter extends AbstractFormatter
  12. {
  13. /**
  14. * IniFormatter constructor.
  15. * @param array $config
  16. */
  17. public function __construct(array $config = [])
  18. {
  19. $config += [
  20. 'file_extension' => '.ser',
  21. 'decode_options' => ['allowed_classes' => [\stdClass::class]]
  22. ];
  23. parent::__construct($config);
  24. }
  25. /**
  26. * Returns options used in decode().
  27. *
  28. * By default only allow stdClass class.
  29. *
  30. * @return array|bool
  31. */
  32. public function getOptions()
  33. {
  34. return $this->getConfig('decode_options');
  35. }
  36. /**
  37. * {@inheritdoc}
  38. * @see FileFormatterInterface::encode()
  39. */
  40. public function encode($data): string
  41. {
  42. return serialize($this->preserveLines($data, ["\n", "\r"], ['\\n', '\\r']));
  43. }
  44. /**
  45. * {@inheritdoc}
  46. * @see FileFormatterInterface::decode()
  47. */
  48. public function decode($data)
  49. {
  50. $decoded = @unserialize($data, $this->getOptions());
  51. if ($decoded === false && $data !== serialize(false)) {
  52. throw new \RuntimeException('Decoding serialized data failed');
  53. }
  54. return $this->preserveLines($decoded, ['\\n', '\\r'], ["\n", "\r"]);
  55. }
  56. /**
  57. * Preserve new lines, recursive function.
  58. *
  59. * @param mixed $data
  60. * @param array $search
  61. * @param array $replace
  62. * @return mixed
  63. */
  64. protected function preserveLines($data, array $search, array $replace)
  65. {
  66. if (\is_string($data)) {
  67. $data = str_replace($search, $replace, $data);
  68. } elseif (\is_array($data)) {
  69. foreach ($data as &$value) {
  70. $value = $this->preserveLines($value, $search, $replace);
  71. }
  72. unset($value);
  73. }
  74. return $data;
  75. }
  76. }