Completed
Push — master ( e467c1...4f24e1 )
by light
39:09 queued 37:32
created

Pubu::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 2
1
<?php
2
3
namespace lxpgw\logger;
4
5
use Yii;
6
use yii\base\InvalidConfigException;
7
use yii\base\Object;
8
use yii\helpers\Json;
9
10
/**
11
 * Pubu.im adapter.
12
 *
13
 * ~~~~
14
 * $pubu = new Pubu(['remote' => 'http://service.pubu.im/dsad']);
15
 * $pubu->send('This is test');
16
 * ~~~
17
 *
18
 * @version 0.0.0
19
 * @author lichunqaing <[email protected]>
20
 */
21
class Pubu extends Object
22
{
23
    /**
24
     * @var string The target remote url send message to.
25
     */
26
    public $remote;
27
28
    /**
29
     * @inheritdoc
30
     */
31 3
    public function init()
32
    {
33 3
        parent::init();
34
35 3
        if (is_null($this->remote)) {
36 1
            throw new InvalidConfigException('$remote must be set.');
37
        }
38 2
    }
39
40
    /**
41
     * @param null|string $text
42
     * @param array $attachments
43
     *
44
     * @return string
45
     */
46 2
    public function send($text = null, $attachments = [])
47
    {
48 2
        $context = stream_context_create([
49
            'http' => [
50 2
                'method' => 'POST',
51 2
                'header' => 'Content-Type:application/json',
52 2
                'content' => Json::encode($this->getPayload($text, $attachments)),
53 2
            ],
54 2
        ]);
55 2
        return file_get_contents($this->remote, false, $context);
56
    }
57
58
    /**
59
     * @param string $text
60
     * @param array $attachments
61
     *
62
     * @return array
63
     */
64 2
    private function getPayload($text, $attachments)
65
    {
66 2
        if ($text == null) {
67 1
            $text = __CLASS__ . '::' . date('Y-m-d H:i');
68 1
        }
69
        $payload = [
70 2
            'text' => $text,
71 2
            'attachments' => $attachments,
72
            //'displayUser' => [
73
            //    'name' => 'FUckaer',
74
            //    'avatarUrl' => 'https://dn-facecdn.qbox.me/assets/1602030042/img/logo-sm.png'
75
            //]
76 2
        ];
77 2
        return $payload;
78
    }
79
}
80
81