Completed
Push — master ( 746a82...9c4ce9 )
by Jivesh
14s queued 10s
created

Slack::send()   C

Complexity

Conditions 7
Paths 17

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
c 5
b 0
f 1
dl 0
loc 34
rs 6.7272
cc 7
eloc 21
nc 17
nop 4
1
<?php
2
3
namespace Gahlawat\Slack;
4
5
use Log;
6
use GuzzleHttp\Client;
7
8
class Slack
9
{
10
    const DEFAULT_ERROR_MESSAGE = 'Slack incoming webhook error';
11
12
    public function send($message, $username=null, $emoji=null, $channel=null)
13
    {
14
        if (! config('slack.incoming-webhook')) {
15
            return;
16
        }
17
18
        $emoji    = trim($emoji);
19
        $channel  = trim($channel);
20
        $username = trim($username);
21
22
        $payload['text']       = $message;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$payload was never initialized. Although not strictly required by PHP, it is generally a good practice to add $payload = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
23
        $payload['username']   = empty($username) ? config('slack.default_username') : $username;
24
        $payload['icon_emoji'] = empty($emoji) ? config('slack.default_emoji') : $emoji;
25
        $payload['channel']    = $channel;
26
27
        $headers = [
28
            'Content-Type' => 'application/json',
29
        ];
30
31
        $guzzleClient = new Client;
32
33
        try {
34
            $response = $guzzleClient->post(config('slack.incoming-webhook'), [
35
                'headers' => $headers,
36
                'body'    => json_encode($payload),
37
            ]);
38
        } catch (\Exception $e) {
39
            Log::error($e->getMessage());
40
        }
41
42
        if (!isset($response) || $response->getStatusCode() != 200) {
43
            Log::error(self::DEFAULT_ERROR_MESSAGE);
44
        }
45
    }
46
}
47