| 1 |
<?php namespace TierPricingTable\Core; |
| 2 |
|
| 3 |
class AdminNotifier { |
| 4 |
|
| 5 |
const ERROR = 'error'; |
| 6 |
|
| 7 |
const WARNING = 'warning'; |
| 8 |
|
| 9 |
const SUCCESS = 'success'; |
| 10 |
|
| 11 |
const INFO = 'info'; |
| 12 |
|
| 13 |
/** |
| 14 |
* Notification key |
| 15 |
* |
| 16 |
* @var string |
| 17 |
*/ |
| 18 |
private $key = 'u2code_admin_notifications'; |
| 19 |
|
| 20 |
/** |
| 21 |
* AdminNotifier constructor. |
| 22 |
*/ |
| 23 |
public function __construct() { |
| 24 |
// Flash messages are processed on admin_init: the current user is not known yet when the plugin boots, |
| 25 |
// and processing on every request would let a frontend visit consume a notice meant for an admin. |
| 26 |
add_action( 'admin_init', array( $this, 'process' ) ); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Per-user notification key. Resolved lazily so the current user is already determined. |
| 31 |
* |
| 32 |
* @return string |
| 33 |
*/ |
| 34 |
private function getKey(): string { |
| 35 |
return $this->key . get_current_user_id(); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Add message to show on admin_notices action |
| 40 |
* |
| 41 |
* @param string $message |
| 42 |
* @param string $type |
| 43 |
* @param bool $isDismissible |
| 44 |
*/ |
| 45 |
public function push( $message, $type = self::SUCCESS, $isDismissible = false ) { |
| 46 |
$dismissible = $isDismissible ? 'is-dismissible' : ''; |
| 47 |
add_action( 'admin_notices', function () use ( $message, $type, $dismissible ) { |
| 48 |
echo "<div class='notice notice-" . esc_attr($type) . ' ' . esc_attr($dismissible) . "'><p>" . wp_kses_post($message) . '</p></div>'; |
| 49 |
} ); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Save flash message to show during next request |
| 54 |
* |
| 55 |
* @param string $message |
| 56 |
* @param string $type |
| 57 |
* @param bool $isDismissible |
| 58 |
*/ |
| 59 |
public function flash( $message, $type = self::SUCCESS, $isDismissible = false ) { |
| 60 |
$message = array( 'message' => $message, 'type' => $type, 'dismissible' => $isDismissible ); |
| 61 |
$messages = get_transient( $this->getKey() ); |
| 62 |
|
| 63 |
if ( ! is_array( $messages ) ) { |
| 64 |
$messages = array(); |
| 65 |
} |
| 66 |
|
| 67 |
$messages[] = $message; |
| 68 |
|
| 69 |
set_transient( $this->getKey(), $messages, MINUTE_IN_SECONDS ); |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* Show flash messages |
| 74 |
*/ |
| 75 |
public function process() { |
| 76 |
$messages = get_transient( $this->getKey() ); |
| 77 |
|
| 78 |
//Resolve conflict with background process |
| 79 |
if ( ! wp_doing_ajax() ) { |
| 80 |
if ( is_array( $messages ) ) { |
| 81 |
|
| 82 |
delete_transient( $this->getKey() ); |
| 83 |
|
| 84 |
foreach ( $messages as $message ) { |
| 85 |
$this->push( $message['message'], $message['type'], $message['dismissible'] ); |
| 86 |
} |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
|