ServerResponse::createResultObjects()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 12
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 22
ccs 9
cts 9
cp 1
crap 3
rs 9.8666
1
<?php
2
3
/**
4
 * This file is part of the TelegramBot package.
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Longman\TelegramBot\Entities;
11
12
use Longman\TelegramBot\Entities\Games\GameHighScore;
13
use Longman\TelegramBot\Request;
14
15
/**
16
 * Class ServerResponse
17
 *
18
 * @link https://core.telegram.org/bots/api#making-requests
19
 *
20
 * @method bool   getOk()          If the request was successful
21
 * @method mixed  getResult()      The result of the query
22
 * @method int    getErrorCode()   Error code of the unsuccessful request
23
 * @method string getDescription() Human-readable description of the result / unsuccessful request
24
 *
25
 * @todo method ResponseParameters getParameters()  Field which can help to automatically handle the error
26
 */
27
class ServerResponse extends Entity
28
{
29
    /**
30
     * ServerResponse constructor.
31
     *
32
     * @param array  $data
33
     * @param string $bot_username
34
     */
35 11
    public function __construct(array $data, string $bot_username = '')
36
    {
37
        // Make sure we don't double-save the raw_data
38 11
        unset($data['raw_data']);
39 11
        $data['raw_data'] = $data;
40
41 11
        $is_ok  = (bool) ($data['ok'] ?? false);
42 11
        $result = $data['result'] ?? null;
43
44 11
        if ($is_ok && is_array($result)) {
45 7
            if ($this->isAssoc($result)) {
46 5
                $data['result'] = $this->createResultObject($result, $bot_username);
47
            } else {
48 2
                $data['result'] = $this->createResultObjects($result, $bot_username);
49
            }
50
        }
51
52 11
        parent::__construct($data, $bot_username);
53 11
    }
54
55
    /**
56
     * Check if array is associative
57
     *
58
     * @link https://stackoverflow.com/a/4254008
59
     *
60
     * @param array $array
61
     *
62
     * @return bool
63
     */
64 7
    protected function isAssoc(array $array): bool
65
    {
66 7
        return count(array_filter(array_keys($array), 'is_string')) > 0;
67
    }
68
69
    /**
70
     * If response is ok
71
     *
72
     * @return bool
73
     */
74 6
    public function isOk(): bool
75
    {
76 6
        return (bool) $this->getOk();
77
    }
78
79
    /**
80
     * Print error
81
     *
82
     * @see https://secure.php.net/manual/en/function.print-r.php
83
     *
84
     * @param bool $return
85
     *
86
     * @return bool|string
87
     */
88
    public function printError($return = false)
89
    {
90
        $error = sprintf('Error N: %s, Description: %s', $this->getErrorCode(), $this->getDescription());
91
92
        if ($return) {
93
            return $error;
94
        }
95
96
        echo $error;
97
98
        return true;
99
    }
100
101
    /**
102
     * Create and return the object of the received result
103
     *
104
     * @param array  $result
105
     * @param string $bot_username
106
     *
107
     * @return Chat|ChatMember|File|Message|User|UserProfilePhotos|WebhookInfo
108
     */
109 5
    private function createResultObject(array $result, string $bot_username)
110
    {
111 5
        $action = Request::getCurrentAction();
112
113
        // We don't need to save the raw_data of the response object!
114 5
        $result['raw_data'] = null;
115
116
        $result_object_types = [
117 5
            'getChat'              => Chat::class,
118
            'getChatMember'        => ChatMember::class,
119
            'getFile'              => File::class,
120
            'getMe'                => User::class,
121
            'getStickerSet'        => StickerSet::class,
122
            'getUserProfilePhotos' => UserProfilePhotos::class,
123
            'getWebhookInfo'       => WebhookInfo::class,
124
        ];
125
126 5
        $object_class = array_key_exists($action, $result_object_types) ? $result_object_types[$action] : Message::class;
127
128 5
        return new $object_class($result, $bot_username);
129
    }
130
131
    /**
132
     * Create and return the objects array of the received result
133
     *
134
     * @param array  $result
135
     * @param string $bot_username
136
     *
137
     * @return BotCommand[]|ChatMember[]|GameHighScore[]|Message[]|Update[]
138
     */
139 2
    private function createResultObjects(array $result, string $bot_username): array
140
    {
141 2
        $results = [];
142 2
        $action  = Request::getCurrentAction();
143
144
        $result_object_types = [
145 2
            'getMyCommands'         => BotCommand::class,
146
            'getChatAdministrators' => ChatMember::class,
147
            'getGameHighScores'     => GameHighScore::class,
148
            'sendMediaGroup'        => Message::class,
149
        ];
150
151 2
        $object_class = array_key_exists($action, $result_object_types) ? $result_object_types[$action] : Update::class;
152
153 2
        foreach ($result as $data) {
154
            // We don't need to save the raw_data of the response object!
155 1
            $data['raw_data'] = null;
156
157 1
            $results[] = new $object_class($data, $bot_username);
158
        }
159
160 2
        return $results;
161
    }
162
}
163