Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
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.

87 lines
2.0KB

  1. <?php
  2. namespace Friendica\Core\Config;
  3. use Exception;
  4. use Friendica\BaseObject;
  5. use Friendica\Database\DBA;
  6. /**
  7. * Preload Configuration Adapter
  8. *
  9. * Minimizes the number of database queries to retrieve configuration values at the cost of memory.
  10. *
  11. * @author Hypolite Petovan <hypolite@mrpetovan.com>
  12. */
  13. class PreloadConfigAdapter extends BaseObject implements IConfigAdapter
  14. {
  15. private $config_loaded = false;
  16. public function __construct()
  17. {
  18. $this->load();
  19. }
  20. public function load($family = 'config')
  21. {
  22. if ($this->config_loaded) {
  23. return;
  24. }
  25. $configs = DBA::select('config', ['cat', 'v', 'k']);
  26. while ($config = DBA::fetch($configs)) {
  27. self::getApp()->setConfigValue($config['cat'], $config['k'], $config['v']);
  28. }
  29. DBA::close($configs);
  30. $this->config_loaded = true;
  31. }
  32. public function get($cat, $k, $default_value = null, $refresh = false)
  33. {
  34. if ($refresh) {
  35. $config = DBA::selectFirst('config', ['v'], ['cat' => $cat, 'k' => $k]);
  36. if (DBA::isResult($config)) {
  37. self::getApp()->setConfigValue($cat, $k, $config['v']);
  38. }
  39. }
  40. $return = self::getApp()->getConfigValue($cat, $k, $default_value);
  41. return $return;
  42. }
  43. public function set($cat, $k, $value)
  44. {
  45. // We store our setting values as strings.
  46. // So we have to do the conversion here so that the compare below works.
  47. // The exception are array values.
  48. $compare_value = !is_array($value) ? (string)$value : $value;
  49. if (self::getApp()->getConfigValue($cat, $k) === $compare_value) {
  50. return true;
  51. }
  52. self::getApp()->setConfigValue($cat, $k, $value);
  53. // manage array value
  54. $dbvalue = is_array($value) ? serialize($value) : $value;
  55. $result = DBA::update('config', ['v' => $dbvalue], ['cat' => $cat, 'k' => $k], true);
  56. if (!$result) {
  57. throw new Exception('Unable to store config value in [' . $cat . '][' . $k . ']');
  58. }
  59. return true;
  60. }
  61. public function delete($cat, $k)
  62. {
  63. self::getApp()->deleteConfigValue($cat, $k);
  64. $result = DBA::delete('config', ['cat' => $cat, 'k' => $k]);
  65. return $result;
  66. }
  67. }