MicrosoftTeams::send()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 12
cp 0
rs 9.2728
c 0
b 0
f 0
cc 5
nc 7
nop 2
crap 30
1
<?php
2
3
namespace NotificationChannels\MicrosoftTeams;
4
5
use Exception;
6
use GuzzleHttp\Client as HttpClient;
7
use GuzzleHttp\Exception\ClientException;
8
use NotificationChannels\MicrosoftTeams\Exceptions\CouldNotSendNotification;
9
use Psr\Http\Message\ResponseInterface;
10
11
class MicrosoftTeams
12
{
13
    /**
14
     * API HTTP client.
15
     *
16
     * @var \GuzzleHttp\Client
17
     */
18
    protected $httpClient;
19
20
    /**
21
     * @param \GuzzleHttp\Client $http
22
     */
23
    public function __construct(HttpClient $http)
24
    {
25
        $this->httpClient = $http;
26
    }
27
28
    /**
29
     * Send a message to a MicrosoftTeams channel.
30
     *
31
     * @param string $url
32
     * @param array $data
33
     *
34
     * @throws CouldNotSendNotification
35
     *
36
     * @return ResponseInterface|null
37
     */
38
    public function send(string $url, array $data): ?ResponseInterface
39
    {
40
        if (! $url) {
41
            throw CouldNotSendNotification::microsoftTeamsWebhookUrlMissing();
42
        }
43
        // convert associative array to numeric array in sections (since ms is otherwise not acception the body structure)
44
        if (isset($data['sections'])) {
45
            $data['sections'] = array_values($data['sections']);
46
        }
47
        try {
48
            $response = $this->httpClient->post($url, [
49
                'json' => $data,
50
            ]);
51
        } catch (ClientException $exception) {
52
            throw CouldNotSendNotification::microsoftTeamsRespondedWithAnError($exception);
53
        } catch (Exception $exception) {
54
            throw CouldNotSendNotification::couldNotCommunicateWithMicrosoftTeams($exception);
55
        }
56
57
        return $response;
58
    }
59
}
60