Passed
Push — master ( fd6438...0db353 )
by Shahrad
02:02
created

WebhookTrait::setWebhook()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 28
rs 9.7333
cc 4
nc 4
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace TelegramBot\Traits;
5
6
use TelegramBot\Entities\Response;
7
use TelegramBot\Exception\TelegramException;
8
use TelegramBot\Request;
9
10
/**
11
 * WebhookTrait class
12
 *
13
 * @link    https://github.com/telegram-bot-php/core
14
 * @author  Shahrad Elahi (https://github.com/shahradelahi)
15
 * @license https://github.com/telegram-bot-php/core/blob/master/LICENSE (MIT License)
16
 */
17
trait WebhookTrait
18
{
19
20
    /**
21
     * Set Webhook for bot
22
     *
23
     * @param string $url
24
     * @param array $data Optional parameters.
25
     * @return Response
26
     * @throws TelegramException
27
     */
28
    public function setWebhook(string $url, array $data = []): Response
29
    {
30
        if ($url === '') {
31
            throw new TelegramException('Hook url is empty!');
32
        }
33
34
        if (!str_starts_with($url, 'https://')) {
35
            throw new TelegramException('Hook url must start with https://');
36
        }
37
38
        $data = array_intersect_key($data, array_flip([
39
            'certificate',
40
            'ip_address',
41
            'max_connections',
42
            'allowed_updates',
43
            'drop_pending_updates',
44
        ]));
45
        $data['url'] = $url;
46
47
        $result = Request::setWebhook($data);
48
49
        if (!$result->isOk()) {
50
            throw new TelegramException(
51
                'Webhook was not set! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
52
            );
53
        }
54
55
        return $result;
56
    }
57
58
    /**
59
     * Delete any assigned webhook
60
     *
61
     * @param array $data
62
     * @return Response
63
     * @throws TelegramException
64
     */
65
    public function deleteWebhook(array $data = []): Response
66
    {
67
        $result = Request::deleteWebhook($data);
68
69
        if (!$result->isOk()) {
70
            throw new TelegramException(
71
                'Webhook was not deleted! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
72
            );
73
        }
74
75
        return $result;
76
    }
77
78
}