-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomTableOption.php
More file actions
66 lines (58 loc) · 1.83 KB
/
CustomTableOption.php
File metadata and controls
66 lines (58 loc) · 1.83 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
<?php
namespace PluginFrame\Core\Services\Options;
use PluginFrame\Core\Services\Options\Interfaces\OptionStorageInterface;
use wpdb;
/**
* Stores options in a custom DB table for high-volume or structured data.
*/
class CustomTableOption implements OptionStorageInterface
{
private wpdb $db;
private string $table;
public function __construct()
{
global $wpdb;
$this->db = $wpdb;
$this->table = $wpdb->prefix . 'plugin_options';
}
public function register(string $key, $default = null, array $args = []): void
{
$exists = $this->db->get_var(
$this->db->prepare("SELECT COUNT(*) FROM {$this->table} WHERE option_key=%s", $key)
);
if (!$exists) {
$this->db->insert(
$this->table,
['option_key' => $key, 'option_value' => maybe_serialize($default)],
['%s','%s']
);
}
}
public function get(string $key, $default = null)
{
$row = $this->db->get_row(
$this->db->prepare("SELECT option_value FROM {$this->table} WHERE option_key=%s", $key),
ARRAY_A
);
return $row ? maybe_unserialize($row['option_value']) : $default;
}
public function update(string $key, $value): bool
{
return (bool) $this->db->update(
$this->table,
['option_value' => maybe_serialize($value)],
['option_key' => $key],
['%s'],
['%s']
);
}
public function delete(string $key): bool
{
return (bool) $this->db->delete($this->table, ['option_key' => $key], ['%s']);
}
public function all(): array
{
$rows = $this->db->get_results("SELECT * FROM {$this->table}", ARRAY_A);
return array_column($rows, 'option_value', 'option_key');
}
}