Passed
Push — master ( 627c19...f3fe5e )
by Armando
03:09
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 Chat|ChatMember|File|Message|User|UserProfilePhotos|WebhookInfo
111
     */
112 5
    private function createResultObject(array $result, string $bot_username): Entity
113
    {
114
        $result_object_types = [
115
            'answerWebAppQuery'               => SentWebAppMessage::class,
116
            'getChat'                         => Chat::class,
117
            'getMyDefaultAdministratorRights' => ChatAdministratorRights::class,
118
            'getChatMember'                   => ChatMemberFactory::class,
119
            'getChatMenuButton'               => MenuButtonFactory::class,
120
            'getFile'                         => File::class,
121
            'getMe'                           => User::class,
122
            'getStickerSet'                   => StickerSet::class,
123
            'getUserProfilePhotos'            => UserProfilePhotos::class,
124
            'getWebhookInfo'                  => WebhookInfo::class,
125
        ];
126
127 5
        $action       = Request::getCurrentAction();
128 5
        $object_class = $result_object_types[$action] ?? Message::class;
129
130
        // We don't need to save the raw_data of the response object!
131 5
        $result['raw_data'] = null;
132
133 5
        return Factory::resolveEntityClass($object_class, $result, $bot_username);
134
    }
135
136
    /**
137
     * Create and return the objects array of the received result
138
     *
139
     * @param array  $results
140
     * @param string $bot_username
141
     *
142
     * @return BotCommand[]|ChatMember[]|GameHighScore[]|Message[]|Update[]
143
     */
144 2
    private function createResultObjects(array $results, string $bot_username): array
145
    {
146
        $result_object_types = [
147
            'getMyCommands'         => BotCommand::class,
148
            'getChatAdministrators' => ChatMemberFactory::class,
149
            'getGameHighScores'     => GameHighScore::class,
150
            'sendMediaGroup'        => Message::class,
151
        ];
152
153 2
        $action       = Request::getCurrentAction();
154 2
        $object_class = $result_object_types[$action] ?? Update::class;
155
156 2
        $objects = [];
157
158 2
        foreach ($results as $result) {
159
            // We don't need to save the raw_data of the response object!
160 1
            $result['raw_data'] = null;
161
162 1
            $objects[] = Factory::resolveEntityClass($object_class, $result, $bot_username);
163
        }
164
165 2
        return $objects;
166
    }
167
}
168