Rest::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 2
1
<?php
2
3
namespace Caikeal\LaravelSms\lib;
4
5
/*
6
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
7
 *
8
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
9
 *  that can be found in the LICENSE file in the root of the web site.
10
 *
11
 *   http://www.yuntongxun.com
12
 *
13
 *  An additional intellectual property rights grant can be found
14
 *  in the file PATENTS.  All contributing project authors may
15
 *  be found in the AUTHORS file in the root of the source tree.
16
 */
17
class Rest
18
{
19
    private $AccountSid;
20
    private $AccountToken;
21
    private $AppId;
22
    private $ServerIP;
23
    private $ServerPort;
24
    private $SoftVersion;
25
    private $Batch;  //时间戳
26
    private $BodyType = 'json'; //包体格式,可填值:json 、xml
27
28
    public function __construct(array $config, $BodyType = 'json')
29
    {
30
        $this->Batch = date('YmdHis');
31
        $this->ServerIP = $config['serverIP'];
32
        $this->ServerPort = $config['serverPort'];
33
        $this->SoftVersion = $config['softVersion'];
34
        $this->AppId = $config['appId'];
35
        $this->AccountSid = $config['accountSid'];
36
        $this->AccountToken = $config['accountToken'];
37
        if (in_array($BodyType, ['xml', 'json'])) {
38
            $this->BodyType = $BodyType;
39
        }
40
    }
41
42
    /**
43
     * 设置主帐号.
44
     *
45
     * @param string $AccountSid   主帐号
46
     * @param string $AccountToken 主帐号Token
47
     */
48
    public function setAccount($AccountSid, $AccountToken)
49
    {
50
        $this->AccountSid = $AccountSid;
51
        $this->AccountToken = $AccountToken;
52
    }
53
54
    /**
55
     * 设置应用ID.
56
     *
57
     * @param string $AppId 应用ID
58
     */
59
    public function setAppId($AppId)
60
    {
61
        $this->AppId = $AppId;
62
    }
63
64
    /**
65
     * 发起HTTPS请求.
66
     *
67
     * @param string $url
68
     * @param mixed  $data
69
     * @param mixed  $header
70
     * @param mixed  $post
71
     *
72
     * @return mixed
73
     */
74 View Code Duplication
    public function curl_post($url, $data, $header, $post = 1)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
75
    {
76
        //初始化curl
77
        $ch = curl_init();
78
        //参数设置
79
        $res = curl_setopt($ch, CURLOPT_URL, $url);
0 ignored issues
show
Unused Code introduced by
$res is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
80
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
81
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
82
        curl_setopt($ch, CURLOPT_HEADER, 0);
83
        curl_setopt($ch, CURLOPT_POST, $post);
84
        if ($post) {
85
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
86
        }
87
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
88
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
89
        $result = curl_exec($ch);
90
        //连接失败
91
        if ($result === false) {
92
            if ($this->BodyType === 'json') {
93
                $result = '{"statusCode":"172001","statusMsg":"网络错误"}';
94
            } else {
95
                $result = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Response><statusCode>172001</statusCode><statusMsg>网络错误</statusMsg></Response>';
96
            }
97
        }
98
        curl_close($ch);
99
100
        return $result;
101
    }
102
103
    /**
104
     * 发送模板短信.
105
     *
106
     * @param string $to     短信接收彿手机号码集合,用英文逗号分开
107
     * @param array  $datas  内容数据
108
     * @param mixed  $tempId 模板Id
109
     *
110
     * @return mixed
111
     */
112
    public function sendTemplateSMS($to, $datas, $tempId)
113
    {
114
        //主帐号鉴权信息验证,对必选参数进行判空。
115
        $auth = $this->accAuth();
116
        if ($auth !== true) {
117
            return $auth;
118
        }
119
        // 拼接请求包体
120
        if ($this->BodyType === 'json') {
121
            $data = '';
122 View Code Duplication
            for ($i = 0; $i < count($datas); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
123
                $data = $data."'".$datas[$i]."',";
124
            }
125
            $body = "{'to':'$to','templateId':'$tempId','appId':'$this->AppId','datas':[".$data.']}';
126
        } else {
127
            $data = '';
128 View Code Duplication
            for ($i = 0; $i < count($datas); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
                $data = $data.'<data>'.$datas[$i].'</data>';
130
            }
131
            $body = "<TemplateSMS>
132
                    <to>$to</to> 
133
                    <appId>$this->AppId</appId>
134
                    <templateId>$tempId</templateId>
135
                    <datas>".$data.'</datas>
136
                  </TemplateSMS>';
137
        }
138
        // 大写的sig参数
139
        $sig = strtoupper(md5($this->AccountSid.$this->AccountToken.$this->Batch));
140
        // 生成请求URL
141
        $url = "https://$this->ServerIP:$this->ServerPort/$this->SoftVersion/Accounts/$this->AccountSid/SMS/TemplateSMS?sig=$sig";
142
        // 生成授权:主帐户Id + 英文冒号 + 时间戳。
143
        $authen = base64_encode($this->AccountSid.':'.$this->Batch);
144
        // 生成包头
145
        $header = ["Accept:application/$this->BodyType", "Content-Type:application/$this->BodyType;charset=utf-8", "Authorization:$authen"];
146
        // 发送请求
147
        $result = $this->curl_post($url, $body, $header);
148 View Code Duplication
        if ($this->BodyType === 'json') {//JSON格式
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
149
            $datas = json_decode($result);
150
        } else { //xml格式
151
            $datas = simplexml_load_string(trim($result, " \t\n\r"));
152
        }
153
        // 重新装填数据
154
        if (isset($datas->templateSMS)) {
155
            $datas->TemplateSMS = $datas->templateSMS;
156
        }
157
158
        return $datas;
159
    }
160
161
    /**
162
     * 语音验证码.
163
     *
164
     * @param mixed $verifyCode     验证码内容,为数字和英文字母,不区分大小写,长度4-8位
165
     * @param mixed $playTimes      播放次数,1-3次
166
     * @param mixed $to             接收号码
167
     * @param mixed $displayNum     显示的主叫号码
168
     * @param mixed $respUrl        语音验证码状态通知回调地址,云通讯平台将向该Url地址发送呼叫结果通知
169
     * @param mixed $lang           语言类型
170
     * @param mixed $userData       第三方私有数据
171
     * @param mixed $welcomePrompt  欢迎提示音,在播放验证码语音前播放此内容(语音文件格式为wav)
172
     * @param mixed $playVerifyCode 语音验证码的内容全部播放此节点下的全部语音文件
173
     *
174
     * @return mixed
175
     */
176
    public function voiceVerify($verifyCode, $playTimes, $to, $displayNum = null, $respUrl = null, $lang = 'zh', $userData = null, $welcomePrompt = null, $playVerifyCode = null)
177
    {
178
        //主帐号鉴权信息验证,对必选参数进行判空。
179
        $auth = $this->accAuth();
180
        if ($auth !== true) {
181
            return $auth;
182
        }
183
        // 拼接请求包体
184
        if ($this->BodyType === 'json') {
185
            $body = "{'appId':'$this->AppId','verifyCode':'$verifyCode','playTimes':'$playTimes','to':'$to','respUrl':'$respUrl','displayNum':'$displayNum',
186
           'lang':'$lang','userData':'$userData','welcomePrompt':'$welcomePrompt','playVerifyCode':'$playVerifyCode'}";
187
        } else {
188
            $body = "<VoiceVerify>
189
                    <appId>$this->AppId</appId>
190
                    <verifyCode>$verifyCode</verifyCode>
191
                    <playTimes>$playTimes</playTimes>
192
                    <to>$to</to>
193
                    <respUrl>$respUrl</respUrl>
194
                    <displayNum>$displayNum</displayNum>
195
                    <lang>$lang</lang>
196
                    <userData>$userData</userData>
197
					<welcomePrompt>$welcomePrompt</welcomePrompt>
198
					<playVerifyCode>$playVerifyCode</playVerifyCode>
199
                  </VoiceVerify>";
200
        }
201
        // 大写的sig参数
202
        $sig = strtoupper(md5($this->AccountSid.$this->AccountToken.$this->Batch));
203
        // 生成请求URL
204
        $url = "https://$this->ServerIP:$this->ServerPort/$this->SoftVersion/Accounts/$this->AccountSid/Calls/VoiceVerify?sig=$sig";
205
        // 生成授权:主帐户Id + 英文冒号 + 时间戳。
206
        $authen = base64_encode($this->AccountSid.':'.$this->Batch);
207
        // 生成包头
208
        $header = ["Accept:application/$this->BodyType", "Content-Type:application/$this->BodyType;charset=utf-8", "Authorization:$authen"];
209
        // 发送请求
210
        $result = $this->curl_post($url, $body, $header);
211 View Code Duplication
        if ($this->BodyType === 'json') {//JSON格式
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
212
            $datas = json_decode($result);
213
        } else { //xml格式
214
            $datas = simplexml_load_string(trim($result, " \t\n\r"));
215
        }
216
217
        return $datas;
218
    }
219
220
    /**
221
     * 主帐号鉴权.
222
     *
223
     * @return mixed
224
     */
225
    public function accAuth()
226
    {
227
        if ($this->ServerIP === '') {
228
            $data = new \stdClass();
229
            $data->statusCode = '172004';
230
            $data->statusMsg = 'IP为空';
231
232
            return $data;
233
        }
234
        if ($this->ServerPort <= 0) {
235
            $data = new \stdClass();
236
            $data->statusCode = '172005';
237
            $data->statusMsg = '端口错误(小于等于0)';
238
239
            return $data;
240
        }
241
        if ($this->SoftVersion === '') {
242
            $data = new \stdClass();
243
            $data->statusCode = '172013';
244
            $data->statusMsg = '版本号为空';
245
246
            return $data;
247
        }
248
        if ($this->AccountSid === '') {
249
            $data = new \stdClass();
250
            $data->statusCode = '172006';
251
            $data->statusMsg = '主帐号为空';
252
253
            return $data;
254
        }
255
        if ($this->AccountToken === '') {
256
            $data = new \stdClass();
257
            $data->statusCode = '172007';
258
            $data->statusMsg = '主帐号令牌为空';
259
260
            return $data;
261
        }
262
        if ($this->AppId === '') {
263
            $data = new \stdClass();
264
            $data->statusCode = '172012';
265
            $data->statusMsg = '应用ID为空';
266
267
            return $data;
268
        }
269
270
        return true;
271
    }
272
}
273