Passed
Push — main ( 4122b8...60aebc )
by Miaad
01:36
created

answer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 28
c 1
b 0
f 0
dl 0
loc 44
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A checkAnswered() 0 4 2
A init() 0 10 1
A checkWebhook() 0 8 3
A sieveData() 0 11 5
1
<?php
2
3
namespace BPT\api\request;
4
5
use BPT\constants\loggerTypes;
6
use BPT\constants\receiver;
7
use BPT\exception\bptException;
8
use BPT\logger;
9
use BPT\settings;
10
11
class answer {
12
    private static bool $is_answered = false;
13
14
    public static function init(string $method,array $data) {
15
        self::checkAnswered();
16
        self::checkWebhook();
17
        self::sieveData($data);
18
        self::$is_answered = true;
19
        $data['method'] = $method;
20
        $payload = json_encode($data);
21
        header('Content-Type: application/json;Content-Length: ' . strlen($payload));
22
        echo $payload;
23
        return true;
24
    }
25
26
    private static function checkAnswered() {
27
        if (self::$is_answered) {
28
            logger::write('You can use answer mode only once for each webhook update , You already did it!',loggerTypes::ERROR);
29
            throw new bptException('ANSWER_MODE_USED');
30
        }
31
    }
32
33
    private static function checkWebhook() {
34
        if(settings::$receiver === receiver::GETUPDATES) {
35
            logger::write('Answer mode only work when receiver is webhook',loggerTypes::ERROR);
36
            throw new bptException('ANSWER_MODE_GETUPDATES');
37
        }
38
        elseif(settings::$multi) {
39
            logger::write('You can not use answer mode when multi setting is on',loggerTypes::ERROR);
40
            throw new bptException('ANSWER_MODE_MULTI');
41
        }
42
    }
43
44
    private static function sieveData(array &$data) {
45
        unset($data['token']);
46
        unset($data['forgot']);
47
        unset($data['return_array']);
48
49
        foreach ($data as $key=>&$value){
50
            if (!isset($value)){
51
                unset($data[$key]);
52
            }
53
            elseif (is_array($value) || is_object($value)){
54
                $value = json_encode($value);
55
            }
56
        }
57
    }
58
}
59