Passed
Push — main ( 1f3d08...95c480 )
by Miaad
10:28
created

answer::isAnswered()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 2
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::checkWebhook();
22
        self::sieveData($data);
23
        self::$is_answered = true;
24
        $data['method'] = $method;
25
        $payload = json_encode($data);
26
        header('Content-Type: application/json;Content-Length: ' . strlen($payload));
27
        echo $payload;
28
        return true;
29
    }
30
31
    public static function isAnswered (): bool {
32
        return self::$is_answered;
33
    }
34
35
    private static function checkWebhook(): void {
36
        if(settings::$receiver === receiver::GETUPDATES) {
37
            logger::write('Answer mode only work when receiver is webhook',loggerTypes::ERROR);
38
            throw new bptException('ANSWER_MODE_GETUPDATES');
39
        }
40
        if(settings::$multi) {
41
            logger::write('You can not use answer mode when multi setting is on',loggerTypes::ERROR);
42
            throw new bptException('ANSWER_MODE_MULTI');
43
        }
44
    }
45
46
    private static function sieveData(array &$data): void {
47
        unset($data['token'],$data['forgot'],$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