Notifications.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace OpenMind\System;
  3. use DB\SQL\Mapper;
  4. class Notifications extends Mapper
  5. {
  6. public const FB_GENERIC = 0x01;
  7. public const FB_IMPORT = 0x02;
  8. public const FB_ADMIN = 0x03;
  9. public const FB_NOTALIVE = 0x0B;
  10. /**
  11. * If you need custom notification or to simply send a command to client use
  12. * FB_CUSTOM_NOTIFICATION+xxx where xxx is a number that identify your notification.
  13. */
  14. public const FB_CUSTOM_NOTIFICATION = 0x4000;
  15. public const FB_REFRESH_FILTERS = self::FB_CUSTOM_NOTIFICATION + 1;
  16. private const TABLE_NAME = 'notifications';
  17. private const CODE_CONDITION = 'code=?';
  18. /**
  19. * Initialize the notification mapper.
  20. *
  21. * @side-effects Connects the mapper to the configured database.
  22. */
  23. public function __construct()
  24. {
  25. global $f3;
  26. parent::__construct($f3->get('DB'), self::TABLE_NAME);
  27. }
  28. /**
  29. * Remove all notifications matching the supplied code.
  30. *
  31. * @param int $code Notification code to remove from the database.
  32. * @return void
  33. * @side-effects Deletes matching notification records.
  34. */
  35. public function Remove(int $code)
  36. {
  37. $this->reset();
  38. $this->erase([self::CODE_CONDITION, $code]);
  39. }
  40. /**
  41. * Remove every notification from the table.
  42. *
  43. * @return void
  44. * @side-effects Truncates the notifications table.
  45. */
  46. public function emptyAll()
  47. {
  48. global $f3;
  49. $f3->get('DB')->exec('TRUNCATE TABLE ' . self::TABLE_NAME);
  50. }
  51. /**
  52. * Send a custom notification to the system.
  53. *
  54. * @param int $code Notification code, such as FB_GENERIC or FB_IMPORT.
  55. * @param string|null $caption Notification caption.
  56. * @param mixed $link Optional notification link.
  57. * @return void
  58. * @side-effects Persists the notification when the code is allowed.
  59. */
  60. public function notify(int $code, string $caption = null, $link = null)
  61. {
  62. if ($code === $this::FB_GENERIC || $this->check($code)) {
  63. $this->reset();
  64. $this->code = $code;
  65. $this->caption = $caption;
  66. $this->link = $link;
  67. $this->save();
  68. }
  69. }
  70. /**
  71. * Check whether a notification with the supplied code exists.
  72. *
  73. * @param int $code Notification code to check.
  74. * @return bool Whether a matching notification exists.
  75. * @side-effects Loads matching records into the mapper.
  76. */
  77. public function check(int $code)
  78. {
  79. $this->load([self::CODE_CONDITION, $code]);
  80. return $this->dry();
  81. }
  82. }