-
Notifications
You must be signed in to change notification settings - Fork 42
/
Module.php
75 lines (61 loc) · 1.98 KB
/
Module.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
namespace webzop\notifications;
use Yii;
use yii\base\InvalidParamException;
class Module extends \yii\base\Module
{
public $channels = [];
public $controllerNamespace = 'webzop\notifications\controllers';
/**
* Send a notification to all channels
*
* @param Notification $notification
* @param array|null $channels
* @return Channel|null return the channel
*/
public function send($notification, array $channels = null){
if($channels === null){
$channels = array_keys($this->channels);
}
foreach ((array)$channels as $id) {
$channel = $this->getChannel($id);
if(!$notification->shouldSend($channel)){
continue;
}
$handle = 'to'.ucfirst($id);
try {
if($notification->hasMethod($handle)){
call_user_func([clone $notification, $handle], $channel);
}
else {
$channel->send(clone $notification);
}
} catch (\Exception $e) {
if (YII_DEBUG) {
throw $e;
}
Yii::warning("Notification sended by channel '$id' has failed: " . $e->getMessage(), __METHOD__);
Yii::warning($e, __METHOD__);
}
}
}
/**
* Gets the channel instance
*
* @param string $id the id of the channel
* @return Channel|null return the channel
* @throws InvalidParamException
*/
public function getChannel($id){
if(!isset($this->channels[$id])){
throw new InvalidParamException("Unknown channel '{$id}'.");
}
if (!is_object($this->channels[$id])) {
$this->channels[$id] = $this->createChannel($id, $this->channels[$id]);
}
return $this->channels[$id];
}
protected function createChannel($id, $config){
return Yii::createObject($config, [$id]);
}
}