Completed
Pull Request — master (#20)
by Casper
06:41
created

Pushover::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
3
namespace NotificationChannels\Pushover;
4
5
use Exception;
6
use GuzzleHttp\Client as HttpClient;
7
use GuzzleHttp\Exception\RequestException;
8
use NotificationChannels\Pushover\Exceptions\CouldNotSendNotification;
9
use NotificationChannels\Pushover\Exceptions\ServiceCommunicationError;
10
11
class Pushover
12
{
13
    /**
14
     * Location of the Pushover API.
15
     *
16
     * @var string
17
     */
18
    protected $pushoverApiUrl = 'https://api.pushover.net/1/messages.json';
19
20
    /**
21
     * The HTTP client instance.
22
     *
23
     * @var \GuzzleHttp\Client
24
     */
25
    protected $http;
26
27
    /**
28
     * Pushover App Token.
29
     *
30
     * @var string
31
     */
32
    protected $token;
33
34
    /**
35
     * @param  HttpClient  $http
36
     * @param  string $token
37
     */
38
    public function __construct(HttpClient $http, $token)
39
    {
40
        $this->http = $http;
41
42
        $this->token = $token;
43
    }
44
45
    /**
46
     * Send Pushover message.
47
     *
48
     * @link  https://pushover.net/api
49
     *
50
     * @param  array  $params
51
     * @return \Psr\Http\Message\ResponseInterface
52
     * @throws CouldNotSendNotification
53
     */
54
    public function send($params)
55
    {
56
        try {
57
            return $this->http->post($this->pushoverApiUrl, [
58
                'form_params' => $this->paramsWithToken($params),
59
            ]);
60
        } catch (RequestException $exception) {
61
            if ($exception->getResponse()) {
62
                throw CouldNotSendNotification::serviceRespondedWithAnError($exception->getResponse());
63
            }
64
            throw ServiceCommunicationError::communicationFailed($exception);
65
        } catch (Exception $exception) {
66
            throw ServiceCommunicationError::communicationFailed($exception);
67
        }
68
    }
69
70
    /**
71
     * Merge token into parameters array.
72
     *
73
     * @param  array  $params
74
     * @return array
75
     */
76
    protected function paramsWithToken($params)
77
    {
78
        return array_merge($params, [
79
            'token' => $this->token,
80
        ]);
81
    }
82
}
83