Slack::send()   B
last analyzed

Complexity

Conditions 5
Paths 9

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 1 Features 2
Metric Value
c 9
b 1
f 2
dl 0
loc 32
rs 8.439
cc 5
eloc 20
nc 9
nop 4
1
<?php
2
3
namespace Gahlawat\Slack;
4
5
use Log;
6
use GuzzleHttp\Client;
7
8
class Slack
9
{
10
    public function send($message, $username = null, $emoji = null, $channel = null)
11
    {
12
        if (! config('slack.incoming-webhook')) {
13
            return;
14
        }
15
16
        $emoji    = trim($emoji);
17
        $channel  = trim($channel);
18
        $username = trim($username);
19
20
        $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...
21
        $payload['username']   = empty($username) ? config('slack.default_username') : $username;
22
        $payload['icon_emoji'] = empty($emoji) ? config('slack.default_emoji') : $emoji;
23
        $payload['channel']    = $channel;
24
25
        $headers = [
26
            'Content-Type' => 'application/json',
27
        ];
28
29
        $guzzleClient = new Client;
30
31
        try {
32
            $response = $guzzleClient->post(config('slack.incoming-webhook'), [
33
                'headers' => $headers,
34
                'body'    => json_encode($payload),
35
            ]);
36
        } catch (\Exception $e) {
37
            Log::error($e->getMessage());
38
        }
39
40
        return $response ?? null;
41
    }
42
}
43