Response::isAssoc()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace TelegramBot\Entities;
4
5
use TelegramBot\Entity;
6
7
/**
8
 * Class Response
9
 *
10
 * @link https://core.telegram.org/bots/api#making-requests
11
 *
12
 * @method bool   getOk()           If the request was successful
13
 * @method mixed  getResult()       The result of the query
14
 * @method int    getErrorCode()    Error code of the unsuccessful request
15
 * @method string getDescription()  Human-readable description of the result / unsuccessful request
16
 */
17
class Response extends Entity
18
{
19
20
    /**
21
     * @var array
22
     */
23
    protected array $requiredFields = [
24
        'ok',
25
        'result',
26
    ];
27
28
    /**
29
     * The raw response from Telegram Bot API.
30
     *
31
     * @var array
32
     */
33
    protected array $response;
34
35
    /**
36
     * Server Response constructor.
37
     *
38
     * @param array $data
39
     */
40
    public function __construct(array $data)
41
    {
42
        $data['raw_data'] = $data;
43
        $this->response = $data;
44
45
        $is_ok = (bool)($data['ok'] ?? false);
46
        $result = $data['result'] ?? null;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
47
48
        if ($is_ok) {
49
            foreach ($this->requiredFields as $field) {
50
                if (!isset($data[$field])) {
51
                    throw new \InvalidArgumentException("The field '{$field}' is required.");
52
                }
53
            }
54
        }
55
56
        parent::__construct($data);
57
    }
58
59
    /**
60
     * If response is ok
61
     *
62
     * @return bool
63
     */
64
    public function isOk(): bool
65
    {
66
        return $this->getOk();
67
    }
68
69
    /**
70
     * Print error
71
     *
72
     * @see https://secure.php.net/manual/en/function.print-r.php
73
     *
74
     * @param bool $return
75
     * @return bool|string
76
     */
77
    public function printError(bool $return = false): bool|string
78
    {
79
        $error = sprintf('Error N: %s, Description: %s', $this->getErrorCode(), $this->getDescription());
80
81
        if ($return) {
82
            return $error;
83
        }
84
85
        echo $error;
86
87
        return true;
88
    }
89
90
    /**
91
     * Check if array is associative
92
     *
93
     * @param array $array
94
     * @return bool
95
     */
96
    protected function isAssoc(array $array): bool
97
    {
98
        return count(array_filter(array_keys($array), 'is_string')) > 0;
99
    }
100
101
}
102