-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin-notices.php
90 lines (70 loc) · 2.1 KB
/
admin-notices.php
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
<?php
/*
Plugin Name: Admin Notices
Plugin URI: https://github.com/jonmcpartland/Admin-Notices/
Description: Useable admin notices.
Author: Jon McPartland
Version: 0.1.0
Author URI: https://jon.mcpart.land
Textdomain: adminnotices
*/
new class {
protected $optionName = 'adminnotices';
public function __construct() {
\add_option( $this->optionName, [], false, true );
$this->create_helper();
\add_action( 'admin_notices', [ $this, 'display_notices' ] );
}
public function display_notices() {
$notices = \get_option( $this->optionName, [] );
$displayed = [];
foreach ( $notices as $notice ) {
if ( ! $this->should_display( $notice ) ) {
continue;
}
$this->render( $notice );
if ( $notice['persist'] ?? false ) {
continue;
}
$displayed[] = $notice;
}
$this->update_notices( $notices, $displayed );
}
protected function should_display( $notice ) {
if ( ! isset( $notice['display'] ) ) {
return false;
}
foreach ( (array) $notice['display'] as $global => $comparison ) {
if ( ! $baseValue = $GLOBALS[ $global ] ?? false || $baseValue !== $comparison ) {
return false;
}
}
return true;
}
protected function render( $notice ) {
vprintf( '<div class="%s"><p>%s</p></div>', [
"notice notice-{$notice['level']} is-dismissible",
$notice['message'],
] );
}
protected function update_notices( $notices, $displayed ) {
// @TODO: ensure data integrity to allow removal of error suppression
$notDisplayed = @array_diff( $notices, $displayed );
\update_option( $this->optionName, $notDisplayed, true );
}
protected function create_helper() {
// @TODO: Move this out of the class
function create_admin_notice( $notice ) {
if ( ! isset( $notice['display'], $notice['level'], $notice['message'] ) ) {
throw new \Exception(
vsprintf( 'The following properties are required for creating an admin notice: "%s", "%s", "%s".', [
'level', 'message', 'display',
] )
);
}
$notices = \get_option( 'adminnotices', [], false, true );
$notices[] = $notice;
\update_option( 'adminnotices', $notices, false, true );
}
}
};