Passed
Push — develop ( ce83ec...1c6380 )
by
unknown
18:21 queued 16:17
created

ServerResponse::isOk()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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