| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <?php
- namespace cx_newsletter;
- use \get_option;
- use \update_option;
- use \delete_option;
- use \exception;
- abstract class settings
- implements settings_interface {
- public function __construct() {
- $this->is_initializated();
- }
- public abstract function get_plugin_version() : int;
- protected abstract function get_options() : array;
- public function get(string $name) : string {
- if (!$this->exists($name)) {
- throw $this->not_exists($name);
- }
- return get_option($this->esc_name($name), $this->get_default($name));
- }
- public function save(string $name, string $content) : self {
- if (!$this->exists($name)) {
- throw $this->not_exists($name);
- }
- update_option($this->esc_name($name), $content);
- return $this;
- }
- public function init() : void {
- foreach ($this->get_options_names() as $name) {
- $this->save($name, $this->get_default($name));
- }
- $this->set_initialization(true);
- }
- public function clean() : void {
- foreach ($this->get_options_names() as $name) {
- $this->drop($name);
- }
- $this->set_initialization(false);
- }
- private function drop(string $name) : void {
- delete_option($this->esc_name($name));
- }
- public function get_default(string $name) : string {
- if (!$this->exists($name)) {
- throw $this->not_exists($name);
- }
- return $this->get_options()[$name];
- }
- private function get_options_names() : array {
- return array_keys($this->get_options());
- }
- private function exists(string $name) : bool {
- return array_key_exists($name, $this->get_options());
- }
- private function not_exists(string $name) : \exception {
- return new exception('Setting with name '.$name.' not exists.');
- }
- private function esc_name(string $name) : string {
- return 'cx_newsletter_option_'.$name;
- }
- public function is_initializated() : bool {
- if ($this->initialization !== null) {
- return $this->initialization;
- }
- $state = get_option($this->initialization_name(), null);
- $this->initialization = ($state === 'yes');
- return $this->is_initializated();
- }
- private function set_initialization(bool $state) : void {
- update_option($this->initialization_name(), 'yes');
- $this->initialization = true;
- if (!$state) {
- delete_option($this->initialization_name());
- $this->initialization = false;
- }
- }
- private function initialization_name() : string {
- return 'cx_newsletter_options_initialization';
- }
-
- protected array $options;
- protected ?bool $initialization = null;
- }
|