YamlConfigManager.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace clagiordano\weblibs\configmanager;
  3. use Exception;
  4. use RuntimeException;
  5. use Symfony\Component\Yaml\Yaml;
  6. /**
  7. * Class YamlConfigManager
  8. * @package clagiordano\weblibs\configmanager
  9. */
  10. class YamlConfigManager extends AbstractConfigManager
  11. {
  12. /**
  13. * Load config data from file and store it into internal property
  14. *
  15. * @param null|string $configFilePath
  16. *
  17. * @return IConfigurable
  18. */
  19. public function loadConfig($configFilePath = null)
  20. {
  21. $this->configFilePath = $configFilePath;
  22. if ($this->checkLoadable()) {
  23. $this->configData = Yaml::parse(file_get_contents($configFilePath));
  24. }
  25. return $this;
  26. }
  27. /**
  28. * Prepare and write config file on disk
  29. *
  30. * @param null|string $configFilePath
  31. * @param bool $autoReloadConfig
  32. *
  33. * @return IConfigurable
  34. * @throws RuntimeException
  35. */
  36. public function saveConfigFile($configFilePath = null, $autoReloadConfig = false)
  37. {
  38. if (is_null($configFilePath)) {
  39. $configFilePath = $this->configFilePath;
  40. }
  41. try {
  42. file_put_contents(
  43. $configFilePath,
  44. Yaml::dump($this->configData, 2, 2)
  45. );
  46. } catch (Exception $exception) {
  47. throw new RuntimeException(
  48. "Failed to write config file to path '{$configFilePath}'\n{$exception->getMessage()}"
  49. );
  50. }
  51. if ($autoReloadConfig) {
  52. $this->loadConfig($configFilePath);
  53. }
  54. return $this;
  55. }
  56. }