← All changes
|
app/Features/UserSettings/Storage/OptionsStorage.php
+76
-0
2.0.1
→
2.1.1
View file →
| @@ -1,0 +1,76 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace Metricool\Features\UserSettings\Storage; | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * This storage uses the wp_options to store and retrieve the UserSettings | |
| 9 | + */ | |
| 10 | +class OptionsStorage extends AbstractStorage | |
| 11 | +{ | |
| 12 | + private string $prefix; | |
| 13 | + | |
| 14 | + public function __construct(string $name, array $config) | |
| 15 | + { | |
| 16 | + if (!isset($config['prefix'])) { | |
| 17 | + throw new \InvalidArgumentException('Prefix is required for OptionsStorage: ' . esc_html($name)); | |
| 18 | + } | |
| 19 | + | |
| 20 | + parent::__construct($name); | |
| 21 | + | |
| 22 | + $this->prefix = $config['prefix']; | |
| 23 | + $this->casing = $config['casing'] ?? 'snakeCase'; | |
| 24 | + } | |
| 25 | + | |
| 26 | + /** | |
| 27 | + * @inheritDoc | |
| 28 | + */ | |
| 29 | + public function get(string $key) | |
| 30 | + { | |
| 31 | + return get_option($this->prefix . $this->convertCase($key)) ?? null; | |
| 32 | + } | |
| 33 | + | |
| 34 | + /** | |
| 35 | + * @inheritDoc | |
| 36 | + */ | |
| 37 | + public function getMultiple(array $keys): array | |
| 38 | + { | |
| 39 | + $result = []; | |
| 40 | + foreach ($keys as $key) { | |
| 41 | + $result[$key] = $this->get($this->convertCase($key)); | |
| 42 | + } | |
| 43 | + | |
| 44 | + return $result; | |
| 45 | + } | |
| 46 | + | |
| 47 | + /** | |
| 48 | + * @inheritDoc | |
| 49 | + */ | |
| 50 | + public function store(string $key, $value): void | |
| 51 | + { | |
| 52 | + update_option($this->prefix . $this->convertCase($key), $value, false); | |
| 53 | + } | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * @inheritDoc | |
| 57 | + */ | |
| 58 | + public function storeMultiple(array $settings): void | |
| 59 | + { | |
| 60 | + foreach ($settings as $key => $value) { | |
| 61 | + $this->store($key, $value); | |
| 62 | + } | |
| 63 | + } | |
| 64 | + | |
| 65 | + /** | |
| 66 | + * @inheritDoc | |
| 67 | + */ | |
| 68 | + public function save(): void | |
| 69 | + { | |
| 70 | + if (empty($this->settings)) { | |
| 71 | + return; | |
| 72 | + } | |
| 73 | + | |
| 74 | + $this->storeMultiple($this->settings); | |
| 75 | + } | |
| 76 | +} | |