Passed
Push — master ( eec373...ce94dc )
by wowiwj
02:15
created

HttpClient::setAccessToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: wangju
5
 * Date: 2019-05-17
6
 * Time: 20:38
7
 */
8
9
namespace DingNotice;
10
11
12
use GuzzleHttp\Client;
13
14
class HttpClient implements SendClient
15
{
16
    protected $client;
17
    protected $config;
18
    /**
19
     * @var string
20
     */
21
    protected $hookUrl = "https://oapi.dingtalk.com/robot/send";
22
23
    /**
24
     * @var string
25
     */
26
    protected $accessToken = "";
27
28
    public function __construct($config)
29
    {
30
        $this->config = $config;
31
        $this->setAccessToken();
32
        $this->client = $this->createClient();
33
    }
34
35
    /**
36
     *
37
     */
38
    public function setAccessToken(){
39
        $this->accessToken = $this->config['token'];
40
    }
41
42
    /**
43
     * create a guzzle client
44
     * @return Client
45
     * @author wangju 2019-05-17 20:25
46
     */
47
    protected function createClient()
48
    {
49
        $client = new Client([
50
            'timeout' => $this->config['timeout'] ?? 2.0,
51
        ]);
52
        return $client;
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    public function getRobotUrl(){
59
        return $this->hookUrl . "?access_token={$this->accessToken}";
60
    }
61
62
    /**
63
     * send message
64
     * @param $url
65
     * @param $params
66
     * @return array
67
     * @author wangju 2019-05-17 20:48
68
     */
69
    public function send($params): array
70
    {
71
        $request = $this->client->post($this->getRobotUrl(), [
72
            'body' => json_encode($params),
73
            'headers' => [
74
                'Content-Type' => 'application/json',
75
            ],
76
            'verify' => $this->config['ssl_verify'] ?? true,
77
        ]);
78
79
        $result = $request->getBody()->getContents();
80
        return json_decode($result, true);
81
    }
82
}
83