Passed
Push — master ( 7ceb6f...b93506 )
by
unknown
05:10
created

Botan::track()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 0
cts 16
cp 0
rs 8.9713
c 0
b 0
f 0
cc 2
eloc 15
nc 2
nop 2
crap 6
1
<?php
2
3
namespace TelegramBot\Api;
4
5
use TelegramBot\Api\Types\Message;
6
7
class Botan
8
{
9
10
    /**
11
     * @var string Tracker url
12
     */
13
    const BASE_URL = 'https://api.botan.io/track';
14
15
    /**
16
     * CURL object
17
     *
18
     * @var
19
     */
20
    protected $curl;
21
22
23
    /**
24
     * Yandex AppMetrica application api_key
25
     *
26
     * @var string
27
     */
28
    protected $token;
29
30
    /**
31
     * Botan constructor
32
     *
33
     * @param string $token
34
     *
35
     * @throws \Exception
36
     */
37 2
    public function __construct($token)
38
    {
39 2
        if (!function_exists('curl_version')) {
40
            throw new Exception('CURL not installed');
41
        }
42
43 2
        if (empty($token) || !is_string($token)) {
44
            throw new InvalidArgumentException('Token should be a string');
45
        }
46
47 2
        $this->token = $token;
48 2
        $this->curl = curl_init();
49 2
    }
50
51
    /**
52
     * Event tracking
53
     *
54
     * @param \TelegramBot\Api\Types\Message $message
55
     * @param string $eventName
56
     *
57
     * @throws \TelegramBot\Api\Exception
58
     * @throws \TelegramBot\Api\HttpException
59
     */
60
    public function track(Message $message, $eventName = 'Message')
61
    {
62
        $uid = $message->getFrom()->getId();
63
64
        $options = [
65
            CURLOPT_URL => self::BASE_URL . "?token={$this->token}&uid={$uid}&name={$eventName}",
66
            CURLOPT_RETURNTRANSFER => true,
67
            CURLOPT_POST => true,
68
            CURLOPT_HTTPHEADER => [
69
                'Content-Type: application/json'
70
            ],
71
            CURLOPT_POSTFIELDS => $message->toJson(),
72
            CURLOPT_TIMEOUT => 5,
73
        ];
74
75
        curl_setopt_array($this->curl, $options);
76
        $result = BotApi::jsonValidate(curl_exec($this->curl), true);
77
78
        BotApi::curlValidate($this->curl);
79
80
        if ($result['status'] !== 'accepted') {
81
            throw new Exception('Error Processing Request');
82
        }
83
    }
84
85
    /**
86
     * Destructor. Close curl
87
     */
88 2
    public function __destruct()
89
    {
90 2
        $this->curl && curl_close($this->curl);
91 2
    }
92
}
93