utils-log.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. // Logging + admin-notice utility for the plugin.
  3. defined('ABSPATH') || exit;
  4. class UtilsLog {
  5. const NOTICE_TRANSIENT_PREFIX = 'studiou_wc_ops_notices_';
  6. const NOTICE_TTL = 300; // 5 minutes — survives slow redirects.
  7. public static function init() {
  8. add_action('admin_notices', array(__CLASS__, 'render_notices'));
  9. }
  10. public static function log($message) {
  11. if (defined('WP_DEBUG') && WP_DEBUG) {
  12. if (is_array($message) || is_object($message)) {
  13. error_log('[studiou-wc-ord-print-statuses] ' . print_r($message, true));
  14. } else {
  15. error_log('[studiou-wc-ord-print-statuses] ' . $message);
  16. }
  17. }
  18. }
  19. /**
  20. * Queue an admin notice for the current user.
  21. * Notices survive the redirect that follows bulk actions and imports.
  22. *
  23. * @param string $message Plain text or pre-escaped HTML (will be wp_kses_post-rendered).
  24. * @param string $type One of: info, success, warning, error.
  25. */
  26. public static function message($message, $type = 'info') {
  27. $user_id = get_current_user_id();
  28. if (!$user_id) {
  29. return;
  30. }
  31. $allowed = array('info', 'success', 'warning', 'error');
  32. if (!in_array($type, $allowed, true)) {
  33. $type = 'info';
  34. }
  35. $key = self::NOTICE_TRANSIENT_PREFIX . $user_id;
  36. $notices = get_transient($key);
  37. if (!is_array($notices)) {
  38. $notices = array();
  39. }
  40. $notices[] = array('message' => (string) $message, 'type' => $type);
  41. set_transient($key, $notices, self::NOTICE_TTL);
  42. }
  43. public static function render_notices() {
  44. $user_id = get_current_user_id();
  45. if (!$user_id) {
  46. return;
  47. }
  48. $key = self::NOTICE_TRANSIENT_PREFIX . $user_id;
  49. $notices = get_transient($key);
  50. if (!is_array($notices) || empty($notices)) {
  51. return;
  52. }
  53. delete_transient($key);
  54. foreach ($notices as $notice) {
  55. $type = isset($notice['type']) ? $notice['type'] : 'info';
  56. $message = isset($notice['message']) ? $notice['message'] : '';
  57. printf(
  58. '<div class="notice notice-%1$s is-dismissible"><p>%2$s</p></div>',
  59. esc_attr($type),
  60. wp_kses_post($message)
  61. );
  62. }
  63. }
  64. }