Preferences.php
2.37 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
<?php
namespace AC;
abstract class Preferences {
/**
* @var int
*/
private $user_id;
/**
* The label for this set of preferences
* @var string
*/
private $label;
/**
* Preferences of this user
* @var array
*/
protected $data = [];
/**
* Retrieves data from DB
* return array|false
*/
abstract protected function load();
/**
* Stores data to DB
* @return bool
*/
abstract public function save();
/**
* @param string $label
* @param null|int $user_id
*/
public function __construct( $label, $user_id = null ) {
if ( null === $user_id ) {
$user_id = get_current_user_id();
}
$this->user_id = (int) $user_id;
$this->label = sanitize_key( (string) $label );
$data = $this->load();
if ( is_array( $data ) ) {
foreach ( $data as $k => $v ) {
$this->set( $k, $v, false );
}
}
}
/**
* Return the key used to store and retrieve this preference
* @return string
*/
protected function get_key() {
return 'ac_preferences_' . $this->label;
}
/**
* @return int
*/
protected function get_user_id() {
return $this->user_id;
}
public function exists( $key ): bool {
return null !== $this->get( $key );
}
/**
* @param string $key
*
* @return mixed|null
*/
public function get( $key ) {
if ( ! isset( $this->data[ $key ] ) ) {
return null;
}
return $this->data[ $key ];
}
/**
* @param string $key
* @param mixed $data
* @param bool $save Immediately save changes to database
*
* @return bool
*/
public function set( $key, $data, $save = true ) {
$this->data[ $key ] = $data;
if ( $save ) {
return $this->save();
}
return true;
}
/**
* @param string $key
* @param bool $save Immediately save changes to database
*
* @return bool
*/
public function delete( $key, $save = true ) {
if ( null === $this->get( $key ) ) {
return false;
}
unset( $this->data[ $key ] );
if ( $save ) {
return $this->save();
}
return true;
}
/**
* Reset site preferences for all users that match on the current label
*/
public function reset_for_all_users() {
if ( empty( $this->label ) ) {
return false;
}
global $wpdb;
$sql = "
DELETE
FROM {$wpdb->usermeta}
WHERE meta_key LIKE %s
";
$sql = $wpdb->prepare( $sql, $wpdb->esc_like( $wpdb->get_blog_prefix() . $this->get_key() ) . '%' );
return (bool) $wpdb->query( $sql );
}
}