Completed
Push — master ( dc5a60...7bba81 )
by Kittinan
06:06
created

LineNotify::send()   C

Complexity

Conditions 9
Paths 13

Size

Total Lines 58
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 58
ccs 0
cts 28
cp 0
rs 6.9928
cc 9
eloc 30
nc 13
nop 3
crap 90

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 1
  public function setToken($token) {
21 1
    $this->token = $token;
22 1
  }
23
24 2
  public function getToken() {
25 2
    return $this->token;
26
  }
27
28
  public function send($text, $imagePath = null, $sticker = 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
    //Message always required
41
    $request_params['multipart'] = [
42
      [
43
        'name' => 'message',
44
        'contents' => $text
45
      ]
46
    ];
47
48
    if (!empty($imagePath)) {
49
      $request_params['multipart'][] = [
50
        'name' => 'imageFile',
51
        'contents' => fopen($imagePath, 'r')
52
      ];
53
    }
54
55
    //https://devdocs.line.me/files/sticker_list.pdf
56
    if (!empty($sticker) 
57
      && !empty($sticker['stickerPackageId']) 
58
      && !empty($sticker['stickerId'])) {
59
      
60
      $request_params['multipart'][] = [
61
        'name' => 'stickerPackageId',
62
        'contents' => $sticker['stickerPackageId']
63
      ];
64
      
65
      $request_params['multipart'][] = [
66
        'name' => 'stickerId',
67
        'contents' => $sticker['stickerId']
68
      ];
69
      
70
    }
71
72
    $response = $this->http->request('POST', LineNotify::API_URL, $request_params);
73
74
    if ($response->getStatusCode() != 200) {
75
      return false;
76
    }
77
78
    $body = (string) $response->getBody();
79
    $json = json_decode($body, true);
80
    if (empty($json['status']) || empty($json['message'])) {
81
      return false;
82
    }
83
84
    return true;
85
  }
86
87
}
88