123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- /**
- * @package Grav\Framework\File\Formatter
- *
- * @copyright Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved.
- * @license MIT License; see LICENSE file for details.
- */
- namespace Grav\Framework\File\Formatter;
- class SerializeFormatter implements FormatterInterface
- {
- /** @var array */
- private $config;
- /**
- * IniFormatter constructor.
- * @param array $config
- */
- public function __construct(array $config = [])
- {
- $this->config = $config + [
- 'file_extension' => '.ser'
- ];
- }
- /**
- * @deprecated 1.5 Use $formatter->getDefaultFileExtension() instead.
- */
- public function getFileExtension()
- {
- return $this->getDefaultFileExtension();
- }
- /**
- * {@inheritdoc}
- */
- public function getDefaultFileExtension()
- {
- $extensions = $this->getSupportedFileExtensions();
- return (string) reset($extensions);
- }
- /**
- * {@inheritdoc}
- */
- public function getSupportedFileExtensions()
- {
- return (array) $this->config['file_extension'];
- }
- /**
- * {@inheritdoc}
- */
- public function encode($data)
- {
- return serialize($this->preserveLines($data, ["\n", "\r"], ['\\n', '\\r']));
- }
- /**
- * {@inheritdoc}
- */
- public function decode($data)
- {
- $decoded = @unserialize($data);
- if ($decoded === false) {
- throw new \RuntimeException('Decoding serialized data failed');
- }
- return $this->preserveLines($decoded, ['\\n', '\\r'], ["\n", "\r"]);
- }
- /**
- * Preserve new lines, recursive function.
- *
- * @param mixed $data
- * @param array $search
- * @param array $replace
- * @return mixed
- */
- protected function preserveLines($data, $search, $replace)
- {
- if (is_string($data)) {
- $data = str_replace($search, $replace, $data);
- } elseif (is_array($data)) {
- foreach ($data as &$value) {
- $value = $this->preserveLines($value, $search, $replace);
- }
- unset($value);
- }
- return $data;
- }
- }
|