forked from MaksimKiselev/yii2-broadcasting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BroadcastEvent.php
108 lines (93 loc) · 2.22 KB
/
BroadcastEvent.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace le0m\broadcasting;
use ReflectionClass;
use ReflectionProperty;
use Yii;
use yii\base\BaseObject;
/**
* Base Broadcast Event class.
*
* @property bool $toOthers Whether to send message only to other users in the channel
*
* @author Maksim Kiselev <[email protected]>
* @author Leo Mainardi <[email protected]>
*/
abstract class BroadcastEvent extends BaseObject
{
/*
* Is it necessary to exclude the current user from the broadcast's recipients
*/
private $_toOthers = false;
/**
* Get the broadcast component
*
* @return \le0m\broadcasting\BroadcastManager
* @throws \yii\base\InvalidConfigException
*/
public function getBroadcastManagerInstance()
{
/** @var \le0m\broadcasting\BroadcastManager $comp */
$comp = Yii::$app->get('broadcasting');
return $comp;
}
/**
* @param bool $value
* @return $this
*/
public function toOthers($value = true)
{
$this->_toOthers = $value;
return $this;
}
/**
* @return bool
*/
public function getToOthers()
{
return $this->_toOthers;
}
/**
* Get the channels the event should broadcast on
*
* @return string|array
*/
abstract public function broadcastOn();
/**
* The event's broadcast name
*
* @return string
*/
public function broadcastAs()
{
return str_replace('\\', '.', static::class);
}
/**
* Get the data to broadcast
*
* @return array
* @throws \ReflectionException
*/
public function broadcastWith()
{
$class = new ReflectionClass($this);
$data = [];
foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
if (!$property->isStatic()) {
$name = $property->getName();
$data[$name] = $property->getValue($this);
}
}
return $data;
}
/**
* Broadcast this event
*/
final public function broadcast()
{
try {
$this->getBroadcastManagerInstance()->dispatchEvent($this);
} catch (\Exception $e) {
Yii::error($e);
}
}
}