Completed
Push — 726-games ( 55c2e1...dff8f6 )
by Armando
05:11 queued 02:43
created

ServerResponse::isAssoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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