CompiledConfig.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. /**
  3. * @package Grav\Common\Config
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Config;
  9. use Grav\Common\File\CompiledYamlFile;
  10. use function is_callable;
  11. /**
  12. * Class CompiledConfig
  13. * @package Grav\Common\Config
  14. */
  15. class CompiledConfig extends CompiledBase
  16. {
  17. /** @var callable Blueprints loader. */
  18. protected $callable;
  19. /** @var bool */
  20. protected $withDefaults = false;
  21. /**
  22. * CompiledConfig constructor.
  23. * @param string $cacheFolder
  24. * @param array $files
  25. * @param string $path
  26. */
  27. public function __construct($cacheFolder, array $files, $path)
  28. {
  29. parent::__construct($cacheFolder, $files, $path);
  30. $this->version = 1;
  31. }
  32. /**
  33. * Set blueprints for the configuration.
  34. *
  35. * @param callable $blueprints
  36. * @return $this
  37. */
  38. public function setBlueprints(callable $blueprints)
  39. {
  40. $this->callable = $blueprints;
  41. return $this;
  42. }
  43. /**
  44. * @param bool $withDefaults
  45. * @return mixed
  46. */
  47. public function load($withDefaults = false)
  48. {
  49. $this->withDefaults = $withDefaults;
  50. return parent::load();
  51. }
  52. /**
  53. * Create configuration object.
  54. *
  55. * @param array $data
  56. * @return void
  57. */
  58. protected function createObject(array $data = [])
  59. {
  60. if ($this->withDefaults && empty($data) && is_callable($this->callable)) {
  61. $blueprints = $this->callable;
  62. $data = $blueprints()->getDefaults();
  63. }
  64. $this->object = new Config($data, $this->callable);
  65. }
  66. /**
  67. * Finalize configuration object.
  68. *
  69. * @return void
  70. */
  71. protected function finalizeObject()
  72. {
  73. $this->object->checksum($this->checksum());
  74. $this->object->timestamp($this->timestamp());
  75. }
  76. /**
  77. * Function gets called when cached configuration is saved.
  78. *
  79. * @return void
  80. */
  81. public function modified()
  82. {
  83. $this->object->modified(true);
  84. }
  85. /**
  86. * Load single configuration file and append it to the correct position.
  87. *
  88. * @param string $name Name of the position.
  89. * @param string $filename File to be loaded.
  90. * @return void
  91. */
  92. protected function loadFile($name, $filename)
  93. {
  94. $file = CompiledYamlFile::instance($filename);
  95. $this->object->join($name, $file->content(), '/');
  96. $file->free();
  97. }
  98. }