Handler.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: NODELOG
  5. * Date: 16/6/7
  6. * Time: 上午10:10
  7. */
  8. namespace common\components\notify;
  9. use common\models\Notify;
  10. use common\models\NotifyCategory;
  11. use Yii;
  12. use yii\base\BaseObject;
  13. use yii\data\ActiveDataProvider;
  14. use yii\helpers\Json;
  15. use yii\helpers\Url;
  16. class Handler extends BaseObject
  17. {
  18. public $notify;
  19. public $notifyCategory;
  20. /**
  21. * @var
  22. */
  23. public $user;
  24. /**
  25. * @var array
  26. */
  27. private $_errors;
  28. /**
  29. * 依赖notify,notifyCategory
  30. * @param Notify $notify
  31. * @param NotifyCategory $notifyCategory
  32. * @param array $config
  33. */
  34. public function __construct(Notify $notify, NotifyCategory $notifyCategory, $config = [])
  35. {
  36. $this->notify = $notify;
  37. $this->notifyCategory = $notifyCategory;
  38. $this->user = Yii::$app->user;
  39. parent::__construct($config);
  40. }
  41. public function category($name)
  42. {
  43. $category_id = $this->notifyCategory->find()->select('id')->where(['name' => $name])->scalar();
  44. $this->notify->category_id = $category_id;
  45. return $this;
  46. }
  47. public function from($uid)
  48. {
  49. $this->notify->from_uid = $uid;
  50. return $this;
  51. }
  52. public function to($uid)
  53. {
  54. $this->notify->to_uid = $uid;
  55. return $this;
  56. }
  57. public function extra($extra)
  58. {
  59. $this->notify->extra = Json::encode($extra);
  60. return $this;
  61. }
  62. public function send()
  63. {
  64. if ($this->notify->to_uid == $this->notify->from_uid) {
  65. return true;
  66. }
  67. if ($this->notify->save() === false) {
  68. $this->_errors = $this->notify->errors;
  69. return false;
  70. }
  71. return true;
  72. }
  73. public function getNoReadNum()
  74. {
  75. return $this->notify->find()->where(['to_uid' => $this->user->id, 'read' => 0])->count();
  76. }
  77. public function getDataProvider()
  78. {
  79. return new ActiveDataProvider([
  80. 'query' => $this->notify->find()->where(['to_uid' => $this->user->id]),
  81. 'sort' => [
  82. 'defaultOrder' => [
  83. 'id' => SORT_DESC
  84. ]
  85. ]
  86. ]);
  87. }
  88. public function readAll()
  89. {
  90. return $this->notify->updateAll(['read' => 1], ['to_uid' => $this->user->id]);
  91. }
  92. public function getErrors()
  93. {
  94. return $this->_errors;
  95. }
  96. }