DataFile.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\File
  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;
  10. use Grav\Framework\File\Interfaces\FileFormatterInterface;
  11. use RuntimeException;
  12. class DataFile extends AbstractFile
  13. {
  14. /** @var FileFormatterInterface */
  15. protected $formatter;
  16. /**
  17. * File constructor.
  18. * @param string $filepath
  19. * @param FileFormatterInterface $formatter
  20. */
  21. public function __construct($filepath, FileFormatterInterface $formatter)
  22. {
  23. parent::__construct($filepath);
  24. $this->formatter = $formatter;
  25. }
  26. /**
  27. * {@inheritdoc}
  28. * @see FileInterface::load()
  29. */
  30. public function load()
  31. {
  32. $raw = parent::load();
  33. try {
  34. return $raw !== false ? $this->formatter->decode($raw) : false;
  35. } catch (RuntimeException $e) {
  36. throw new RuntimeException(sprintf("Failed to load file '%s': %s", $this->getFilePath(), $e->getMessage()), $e->getCode(), $e);
  37. }
  38. }
  39. /**
  40. * {@inheritdoc}
  41. * @see FileInterface::save()
  42. */
  43. public function save($data): void
  44. {
  45. if (\is_string($data)) {
  46. // Make sure that the string is valid data.
  47. try {
  48. $this->formatter->decode($data);
  49. } catch (RuntimeException $e) {
  50. throw new RuntimeException(sprintf("Failed to save file '%s': %s", $this->getFilePath(), $e->getMessage()), $e->getCode(), $e);
  51. }
  52. $encoded = $data;
  53. } else {
  54. $encoded = $this->formatter->encode($data);
  55. }
  56. parent::save($encoded);
  57. }
  58. }