Pusher   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 0
dl 0
loc 75
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A trigger() 0 8 2
A sendRequest() 0 27 2
A getPusherUrl() 0 8 1
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['channels'] = 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
        $jsonData = json_encode($data);
45
46
        $ch = curl_init($url);
47
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
48
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
49
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
50
        curl_setopt(
51
            $ch,
52
            CURLOPT_HTTPHEADER,
53
            [
54
                'Content-Type: application/json',
55
                'Content-Length: '.strlen($jsonData),
56
            ]
57
        );
58
59
        $response = curl_exec($ch);
60
61
        if ($response === false) {
62
            logger()->error('[LaravelUnicomponent] Pusher Send Request Error, data:'.$jsonData);
63
64
            return false;
65
        }
66
67
        return $response;
68
    }
69
70
    /**
71
     * Get Pusher Url.
72
     *
73
     * @author reallyli <[email protected]>
74
     * @since 2018/11/20
75
     * @return string
76
     */
77
    protected function getPusherUrl()
78
    {
79
        $pusherUrl = config('unicomponent.components.pusher.configs.pusher_url');
80
81
        throw_unless(filter_var($pusherUrl, FILTER_VALIDATE_URL), '\Exception', 'pusher url illegal');
82
83
        return $pusherUrl;
84
    }
85
}
86