You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

143 lines
2.6 KiB

5 years ago
  1. <?php namespace Efriandika\LaravelSettings;
  2. /**
  3. * Class Cache
  4. * @package Efriandika\LaravelSettings
  5. */
  6. class Cache
  7. {
  8. /**
  9. * Path to cache file
  10. *
  11. * @var string
  12. */
  13. protected $cacheFile;
  14. /**
  15. * Cached Settings
  16. *
  17. * @var array
  18. */
  19. protected $settings;
  20. /**
  21. * Constructor
  22. *
  23. * @param string $cacheFile
  24. */
  25. public function __construct($cacheFile)
  26. {
  27. $this->cacheFile = $cacheFile;
  28. $this->checkCacheFile();
  29. $this->settings = $this->getAll();
  30. }
  31. /**
  32. * Sets a value
  33. *
  34. * @param $key
  35. * @param $value
  36. *
  37. * @return mixed
  38. */
  39. public function set($key, $value)
  40. {
  41. $this->settings[$key] = $value;
  42. $this->store();
  43. return $value;
  44. }
  45. /**
  46. * Gets a value
  47. *
  48. * @param $key
  49. * @param null $default
  50. *
  51. * @return mixed
  52. */
  53. public function get($key, $default = null)
  54. {
  55. return (array_key_exists($key, $this->settings) ? $this->settings[$key] : $default);
  56. }
  57. /**
  58. * Checks if $key is cached
  59. *
  60. * @param $key
  61. *
  62. * @return bool
  63. */
  64. public function hasKey($key)
  65. {
  66. return array_key_exists($key, $this->settings);
  67. }
  68. /**
  69. * Gets all cached settings
  70. *
  71. * @return array
  72. */
  73. public function getAll()
  74. {
  75. $values = json_decode(file_get_contents($this->cacheFile), true);
  76. foreach ($values as $key => $value) {
  77. $values[$key] = unserialize($value);
  78. }
  79. return $values;
  80. }
  81. /**
  82. * Stores all settings to the cache file
  83. *
  84. * @return void
  85. */
  86. private function store()
  87. {
  88. $settings = [];
  89. foreach ($this->settings as $key => $value) {
  90. $settings[$key] = serialize($value);
  91. }
  92. file_put_contents($this->cacheFile, json_encode($settings));
  93. }
  94. /**
  95. * Removes a value
  96. *
  97. * @return void
  98. */
  99. public function forget($key)
  100. {
  101. if (array_key_exists($key, $this->settings)) {
  102. unset($this->settings[$key]);
  103. }
  104. $this->store();
  105. }
  106. /**
  107. * Removes all values
  108. *
  109. * @return void
  110. */
  111. public function flush()
  112. {
  113. file_put_contents($this->cacheFile, json_encode([]));
  114. // fixed the set after immediately the flush, should be returned empty
  115. $this->settings = [];
  116. }
  117. /**
  118. * Checks if the cache file exists and creates it if not
  119. *
  120. * @return void
  121. */
  122. private function checkCacheFile()
  123. {
  124. if (!file_exists($this->cacheFile)) {
  125. $this->flush();
  126. }
  127. }
  128. }