|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @link http://www.tintsoft.com/ |
|
4
|
|
|
* @copyright Copyright (c) 2012 TintSoft Technology Co. Ltd. |
|
5
|
|
|
* @license http://www.tintsoft.com/license/ |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
namespace yuncms\broadcast; |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
use Yii; |
|
12
|
|
|
use yii\base\BaseObject; |
|
13
|
|
|
use yii\base\ErrorHandler; |
|
14
|
|
|
use yuncms\helpers\Json; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Class BaseMessage |
|
18
|
|
|
* |
|
19
|
|
|
* @author Tongle Xu <[email protected]> |
|
20
|
|
|
* @since 3.0 |
|
21
|
|
|
*/ |
|
22
|
|
|
abstract class BaseMessage extends BaseObject implements MessageInterface |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* @var BroadcastInterface the broadcast instance that created this message. |
|
26
|
|
|
* For independently created messages this is `null`. |
|
27
|
|
|
*/ |
|
28
|
|
|
public $broadcast; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var array |
|
32
|
|
|
*/ |
|
33
|
|
|
public $body; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Sends this broadcast message. |
|
37
|
|
|
* @param BroadcastInterface $broadcast the broadcast that should be used to send this message. |
|
38
|
|
|
* If no broadcast is given it will first check if [[broadcast]] is set and if not, |
|
39
|
|
|
* the "broadcast" application component will be used instead. |
|
40
|
|
|
* @return bool whether this message is sent successfully. |
|
41
|
|
|
*/ |
|
42
|
|
|
public function send(BroadcastInterface $broadcast = null) |
|
43
|
|
|
{ |
|
44
|
|
|
if ($broadcast === null && $this->broadcast === null) { |
|
45
|
|
|
$broadcast = Yii::$app->getBroadcast(); |
|
46
|
|
|
} elseif ($broadcast === null) { |
|
47
|
|
|
$broadcast = $this->broadcast; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
return $broadcast->send($this); |
|
|
|
|
|
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Returns string representation of this message. |
|
55
|
|
|
* @return string the string representation of this message. |
|
56
|
|
|
*/ |
|
57
|
|
|
public function toString() |
|
58
|
|
|
{ |
|
59
|
|
|
return Json::encode($this->body); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* PHP magic method that returns the string representation of this object. |
|
64
|
|
|
* @return string the string representation of this object. |
|
65
|
|
|
*/ |
|
66
|
|
|
public function __toString() |
|
67
|
|
|
{ |
|
68
|
|
|
// __toString cannot throw exception |
|
69
|
|
|
// use trigger_error to bypass this limitation |
|
70
|
|
|
try { |
|
71
|
|
|
return $this->toString(); |
|
72
|
|
|
} catch (\Exception $e) { |
|
73
|
|
|
ErrorHandler::convertExceptionToError($e); |
|
74
|
|
|
return ''; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
} |