1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: uniqueway |
5
|
|
|
* Date: 2018/11/20 |
6
|
|
|
* Time: δΈε11:39. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Reallyli\LaravelUnicomponent\Components\Pusher; |
10
|
|
|
|
11
|
|
|
class Pusher |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* trigger. |
15
|
|
|
* |
16
|
|
|
* @author reallyli <[email protected]> |
17
|
|
|
* @since 2018/11/20 |
18
|
|
|
* @param mixed $channels |
19
|
|
|
* @param string $eventName |
20
|
|
|
* @param array $data |
21
|
|
|
* @param array $params |
22
|
|
|
* @return mixed |
23
|
|
|
*/ |
24
|
|
|
public function trigger($channels, string $eventName, array $data, array $params = []) |
25
|
|
|
{ |
26
|
|
|
$params['channel'] = is_string($channels) ? [$channels] : (array) $channels; |
27
|
|
|
$params['data'] = $data; |
28
|
|
|
$params['name'] = $eventName; |
29
|
|
|
|
30
|
|
|
$this->sendRequest($this->getPusherUrl(), $params); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Send Request. |
35
|
|
|
* |
36
|
|
|
* @author reallyli <[email protected]> |
37
|
|
|
* @since 2018/11/20 |
38
|
|
|
* @param string $url |
39
|
|
|
* @param array $data |
40
|
|
|
* @return mixed |
41
|
|
|
*/ |
42
|
|
|
protected function sendRequest(string $url, array $data) |
43
|
|
|
{ |
44
|
|
|
$ch = curl_init($url); |
45
|
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); |
46
|
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); |
47
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
48
|
|
|
curl_setopt( |
49
|
|
|
$ch, |
50
|
|
|
CURLOPT_HTTPHEADER, |
51
|
|
|
[ |
52
|
|
|
'Content-Type: application/json', |
53
|
|
|
'Content-Length: '.strlen($data), |
54
|
|
|
] |
55
|
|
|
); |
56
|
|
|
|
57
|
|
|
$response = curl_exec($ch); |
58
|
|
|
|
59
|
|
|
if ($response === false) { |
60
|
|
|
logger()->error('[LaravelUnicomponent] Pusher Send Request Error, data:'.json_encode($data)); |
61
|
|
|
|
62
|
|
|
return false; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $response; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Get Pusher Url. |
70
|
|
|
* |
71
|
|
|
* @author reallyli <[email protected]> |
72
|
|
|
* @since 2018/11/20 |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
|
|
protected function getPusherUrl() |
76
|
|
|
{ |
77
|
|
|
$pusherUrl = config('unicomponent.pusher.configs.pusher_url'); |
78
|
|
|
|
79
|
|
|
throw_unless(filter_var($pusherUrl, FILTER_VALIDATE_URL), '\Exception', 'pusher url illegal'); |
80
|
|
|
|
81
|
|
|
return $pusherUrl; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|