Passed
Push — main ( 926a07...7834cc )
by Miaad
10:19
created

answer::checkAnswered()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace BPT\telegram\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
/**
12
 * answer class , part of request class for handling request based on answering to webhook directly
13
 */
14
class answer {
15
    private static bool $is_answered = false;
16
17
    /**
18
     * @internal Only for BPT self usage , Don't use it in your source!
19
     */
20
    public static function init(string $method,array $data): bool {
21
        self::checkAnswered();
22
        self::checkWebhook();
23
        self::sieveData($data);
24
        self::$is_answered = true;
25
        $data['method'] = $method;
26
        $payload = json_encode($data);
27
        header('Content-Type: application/json;Content-Length: ' . strlen($payload));
28
        echo $payload;
29
        return true;
30
    }
31
32
    private static function checkAnswered(): void {
33
        if (self::$is_answered) {
34
            logger::write('You can use answer mode only once for each webhook update , You already did it!',loggerTypes::ERROR);
35
            throw new bptException('ANSWER_MODE_USED');
36
        }
37
    }
38
39
    private static function checkWebhook(): void {
40
        if(settings::$receiver === receiver::GETUPDATES) {
41
            logger::write('Answer mode only work when receiver is webhook',loggerTypes::ERROR);
42
            throw new bptException('ANSWER_MODE_GETUPDATES');
43
        }
44
        elseif(settings::$multi) {
45
            logger::write('You can not use answer mode when multi setting is on',loggerTypes::ERROR);
46
            throw new bptException('ANSWER_MODE_MULTI');
47
        }
48
    }
49
50
    private static function sieveData(array &$data): void {
51
        unset($data['token'],$data['forgot'],$data['return_array']);
52
53
        foreach ($data as $key=>&$value){
54
            if (!isset($value)){
55
                unset($data[$key]);
56
            }
57
            elseif (is_array($value) || is_object($value)){
58
                $value = json_encode($value);
59
            }
60
        }
61
    }
62
}
63