Completed
Push — master ( 9d233b...7e7cc3 )
by Kittinan
01:47
created

LineNotify::send()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 41
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 41
rs 8.439
cc 6
eloc 22
nc 7
nop 2
1
<?php
2
3
namespace KS\Line;
4
5
use GuzzleHttp\Client;
6
7
class LineNotify {
8
9
  const API_URL = 'https://notify-api.line.me/api/notify';
10
11
  private $token = null;
12
  private $http = null;
13
14
  public function __construct($token) {
15
16
    $this->token = $token;
17
    $this->http = new Client();
18
  }
19
20
  public function setToken($token) {
21
    $this->token = $token;
22
  }
23
24
  public function getToken() {
25
    return $this->token;
26
  }
27
28
  public function send($text, $imagePath = null) {
29
30
    if (empty($text)) {
31
      return false;
32
    }
33
34
    $request_params = [
35
      'headers' => [
36
        'Authorization' => 'Bearer ' . $this->token,
37
      ],
38
    ];
39
40
    if (!empty($imagePath)) {
41
      $request_params['multipart'] = [
42
        [
43
          'name' => 'message',
44
          'contents' => $text
45
        ],
46
        [
47
          'name' => 'imageFile',
48
          'contents' => fopen($imagePath, 'r')
49
        ],
50
      ];
51
    } else {
52
      $request_params['form_params'] = ['message' => $text];
53
    }
54
55
    $response = $this->http->request('POST', LineNotify::API_URL, $request_params);
56
57
    if ($response->getStatusCode() != 200) {
58
      return false;
59
    }
60
61
    $body = (string) $response->getBody();
62
    $json = json_decode($body, true);
63
    if (empty($json['status']) || empty($json['message'])) {
64
      return false;
65
    }
66
67
    return true;
68
  }
69
70
}
71