class-wcmq-state.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * enabled -> draining -> disabled state machine.
  4. *
  5. * Disabling must never strand mail that is already queued: the interceptor
  6. * stops queueing immediately, but the worker keeps draining what is there.
  7. *
  8. * @package studiou-wc-mail-queue
  9. * @copyright 2026 QUADARAX
  10. * @author Dalibor Votruba <dvotruba@quadarax.com>
  11. * @license GPL-2.0-or-later
  12. */
  13. defined( 'ABSPATH' ) || exit;
  14. /**
  15. * Class Studiou_WCMQ_State
  16. */
  17. class Studiou_WCMQ_State {
  18. /**
  19. * Register hooks.
  20. */
  21. public static function init() {
  22. // A queue emptied by retention or by manual deletion still needs to settle.
  23. add_action( 'admin_init', array( __CLASS__, 'maybe_settle' ) );
  24. }
  25. /**
  26. * Current state.
  27. *
  28. * @return string
  29. */
  30. public static function get() {
  31. return Studiou_WCMQ_Settings::state();
  32. }
  33. /**
  34. * Whether new mail should be queued right now.
  35. *
  36. * @return bool
  37. */
  38. public static function is_queueing() {
  39. return Studiou_WCMQ_Settings::STATE_ENABLED === self::get();
  40. }
  41. /**
  42. * Turn queueing on.
  43. */
  44. public static function enable() {
  45. Studiou_WCMQ_Settings::set_state( Studiou_WCMQ_Settings::STATE_ENABLED );
  46. Studiou_WCMQ_DB::log( 'info', 'Queue enabled.' );
  47. }
  48. /**
  49. * Turn queueing off, draining first if anything is in flight.
  50. */
  51. public static function disable() {
  52. if ( Studiou_WCMQ_DB::count_unfinished() > 0 ) {
  53. Studiou_WCMQ_Settings::set_state( Studiou_WCMQ_Settings::STATE_DRAINING );
  54. Studiou_WCMQ_DB::log( 'info', 'Queue draining; new mail sends synchronously.' );
  55. return;
  56. }
  57. Studiou_WCMQ_Settings::set_state( Studiou_WCMQ_Settings::STATE_DISABLED );
  58. Studiou_WCMQ_DB::log( 'info', 'Queue disabled.' );
  59. }
  60. /**
  61. * Move draining -> disabled once nothing is left in flight.
  62. *
  63. * Called by the worker after each send and on admin_init.
  64. */
  65. public static function maybe_settle() {
  66. if ( Studiou_WCMQ_Settings::STATE_DRAINING !== self::get() ) {
  67. return;
  68. }
  69. if ( Studiou_WCMQ_DB::count_unfinished() > 0 ) {
  70. return;
  71. }
  72. Studiou_WCMQ_Settings::set_state( Studiou_WCMQ_Settings::STATE_DISABLED );
  73. Studiou_WCMQ_DB::log( 'info', 'Queue drained; now disabled.' );
  74. }
  75. }