|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @copyright Anton Tuyakhov <[email protected]> |
|
4
|
|
|
*/ |
|
5
|
|
|
|
|
6
|
|
|
namespace tuyakhov\notifications\channels; |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
use tuyakhov\notifications\messages\DatabaseMessage; |
|
10
|
|
|
use tuyakhov\notifications\NotifiableInterface; |
|
11
|
|
|
use tuyakhov\notifications\NotificationInterface; |
|
12
|
|
|
use yii\base\Component; |
|
13
|
|
|
use yii\base\InvalidConfigException; |
|
14
|
|
|
use yii\db\BaseActiveRecord; |
|
15
|
|
|
use yii\helpers\Json; |
|
16
|
|
|
|
|
17
|
|
|
class ActiveRecordChannel extends Component implements ChannelInterface |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* @var BaseActiveRecord|string |
|
21
|
|
|
*/ |
|
22
|
|
|
public $model = 'tuyakhov\notifications\models\Notification'; |
|
23
|
|
|
|
|
24
|
|
|
public function send(NotifiableInterface $recipient, NotificationInterface $notification) |
|
25
|
|
|
{ |
|
26
|
|
|
$model = \Yii::createObject($this->model); |
|
|
|
|
|
|
27
|
|
|
|
|
28
|
|
|
if (!$model instanceof BaseActiveRecord) { |
|
29
|
|
|
throw new InvalidConfigException('Model class must extend from \\yii\\db\\BaseActiveRecord'); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** @var DatabaseMessage $message */ |
|
33
|
|
|
$message = $notification->exportFor('database'); |
|
34
|
|
|
list($notifiableType, $notifiableId) = $recipient->routeNotificationFor('database'); |
|
35
|
|
|
$data = [ |
|
36
|
|
|
'level' => $message->level, |
|
37
|
|
|
'subject' => $message->subject, |
|
38
|
|
|
'body' => $message->body, |
|
39
|
|
|
'notifiable_type' => $notifiableType, |
|
40
|
|
|
'notifiable_id' => $notifiableId, |
|
41
|
|
|
'data' => Json::encode($message->data), |
|
42
|
|
|
]; |
|
43
|
|
|
|
|
44
|
|
|
if ($model->load($data, '')) { |
|
45
|
|
|
return $model->insert(); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return false; |
|
49
|
|
|
} |
|
50
|
|
|
} |