Completed
Push — bot_api_3.0 ( 7bd219...c1af4b )
by Armando
03:09
created

ServerResponse::isAssoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
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 9
    public function __construct(array $data, $bot_username)
34
    {
35
        // Make sure we don't double-save the raw_data
36 9
        unset($data['raw_data']);
37 9
        $data['raw_data'] = $data;
38
39 9
        $is_ok  = isset($data['ok']) ? (bool) $data['ok'] : false;
40 9
        $result = isset($data['result']) ? $data['result'] : null;
41
42 9
        if ($is_ok && is_array($result)) {
43 6
            if ($this->isAssoc($result)) {
44 4
                $data['result'] = $this->createResultObject($result, $bot_username);
45
            } else {
46 2
                $data['result'] = $this->createResultObjects($result, $bot_username);
47
            }
48
        }
49
50 9
        parent::__construct($data, $bot_username);
51 9
    }
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 6
    protected function isAssoc(array $array)
63
    {
64 6
        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 4
    private function createResultObject($result, $bot_username)
109
    {
110
        // We don't need to save the raw_data of the response object!
111 4
        $result['raw_data'] = null;
112
113
        $result_object_types = [
114 4
            'total_count' => 'UserProfilePhotos', //Response from getUserProfilePhotos
115
            'file_id'     => 'File',              //Response from getFile
116
            'title'       => 'Chat',              //Response from getChat
117
            'username'    => 'User',              //Response from getMe
118
            'user'        => 'ChatMember',        //Response from getChatMember
119
            'url'         => 'WebhookInfo',       //Response from getWebhookInfo
120
        ];
121 4
        foreach ($result_object_types as $type => $object_class) {
122 4
            if (isset($result[$type])) {
123 2
                $object_class = __NAMESPACE__ . '\\' . $object_class;
124
125 4
                return new $object_class($result);
126
            }
127
        }
128
129
        //Response from sendMessage
130 2
        return new Message($result, $bot_username);
131
    }
132
133
    /**
134
     * Create and return the objects array of the received result
135
     *
136
     * @param array  $result
137
     * @param string $bot_username
138
     *
139
     * @return null|\Longman\TelegramBot\Entities\ChatMember[]|\Longman\TelegramBot\Entities\Update[]
140
     * @throws \Longman\TelegramBot\Exception\TelegramException
141
     */
142 2
    private function createResultObjects($result, $bot_username)
143
    {
144 2
        $results = [];
145 2
        if (isset($result[0]['user'])) {
146
            //Response from getChatAdministrators
147
            foreach ($result as $user) {
148
                // We don't need to save the raw_data of the response object!
149
                $user['raw_data'] = null;
150
151
                $results[] = new ChatMember($user);
152
            }
153
        } else {
154
            //Get Update
155 2
            foreach ($result as $update) {
156
                // We don't need to save the raw_data of the response object!
157 1
                $update['raw_data'] = null;
158
159 1
                $results[] = new Update($update, $bot_username);
160
            }
161
        }
162
163 2
        return $results;
164
    }
165
}
166