persistent-module.php
1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
abstract class amePersistentModule extends ameModule {
/**
* @var string Database option where module settings are stored.
*/
protected $optionName = '';
/**
* @var array|null Module settings. NULL when settings haven't been loaded yet.
*/
protected $settings = null;
/**
* @var array Default module settings.
*/
protected $defaultSettings = array();
public function __construct($menuEditor) {
if ( $this->optionName === '' ) {
throw new LogicException(__CLASS__ . '::$optionName is an empty string. You must set it to a valid option name.');
}
parent::__construct($menuEditor);
}
public function loadSettings() {
if ( isset($this->settings) ) {
return $this->settings;
}
$json = $this->getScopedOption($this->optionName, null);
if ( is_string($json) && !empty($json) ) {
$settings = json_decode($json, true);
} else {
$settings = array();
}
$this->settings = array_merge($this->defaultSettings, $settings);
return $this->settings;
}
public function saveSettings() {
$settings = wp_json_encode($this->settings);
//Save per site or site-wide based on plugin configuration.
$this->setScopedOption($this->optionName, $settings);
}
public function mergeSettingsWith($newSettings) {
$this->settings = array_merge($this->loadSettings(), $newSettings);
return $this->settings;
}
protected function getTemplateVariables($templateName) {
$variables = parent::getTemplateVariables($templateName);
if ( $templateName === $this->moduleId ) {
$variables = array_merge(
$variables,
array(
'settings' => $this->loadSettings(),
)
);
}
return $variables;
}
}