Completed
Push — master ( 2cfb8a...695e63 )
by Armando
01:30
created

ServerResponse   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 137
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
wmc 15
lcom 0
cbo 2
dl 0
loc 137
ccs 30
cts 36
cp 0.8333
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 6
A isAssoc() 0 4 1
A isOk() 0 4 1
A printError() 0 12 2
A createResultObject() 0 21 2
A createResultObjects() 0 22 3
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
use Longman\TelegramBot\Entities\Games\GameHighScore;
12
use Longman\TelegramBot\Request;
13
14
/**
15
 * Class ServerResponse
16
 *
17
 * @link https://core.telegram.org/bots/api#making-requests
18
 *
19
 * @method bool   getOk()          If the request was successful
20
 * @method mixed  getResult()      The result of the query
21
 * @method int    getErrorCode()   Error code of the unsuccessful request
22
 * @method string getDescription() Human-readable description of the result / unsuccessful request
23
 *
24
 * @todo method ResponseParameters getParameters()  Field which can help to automatically handle the error
25
 */
26
class ServerResponse extends Entity
27
{
28
    /**
29
     * ServerResponse constructor.
30
     *
31
     * @param array  $data
32
     * @param string $bot_username
33
     *
34
     * @throws \Longman\TelegramBot\Exception\TelegramException
35
     */
36 10
    public function __construct(array $data, $bot_username)
37
    {
38
        // Make sure we don't double-save the raw_data
39 10
        unset($data['raw_data']);
40 10
        $data['raw_data'] = $data;
41
42 10
        $is_ok  = isset($data['ok']) ? (bool) $data['ok'] : false;
43 10
        $result = isset($data['result']) ? $data['result'] : null;
44
45 10
        if ($is_ok && is_array($result)) {
46 7
            if ($this->isAssoc($result)) {
47 5
                $data['result'] = $this->createResultObject($result, $bot_username);
48
            } else {
49 2
                $data['result'] = $this->createResultObjects($result, $bot_username);
50
            }
51
        }
52
53 10
        parent::__construct($data, $bot_username);
54 10
    }
55
56
    /**
57
     * Check if array is associative
58
     *
59
     * @link https://stackoverflow.com/a/4254008
60
     *
61
     * @param array $array
62
     *
63
     * @return bool
64
     */
65 7
    protected function isAssoc(array $array)
66
    {
67 7
        return count(array_filter(array_keys($array), 'is_string')) > 0;
68
    }
69
70
    /**
71
     * If response is ok
72
     *
73
     * @return bool
74
     */
75 5
    public function isOk()
76
    {
77 5
        return (bool) $this->getOk();
78
    }
79
80
    /**
81
     * Print error
82
     *
83
     * @see https://secure.php.net/manual/en/function.print-r.php
84
     *
85
     * @param bool $return
86
     *
87
     * @return bool|string
88
     */
89
    public function printError($return = false)
90
    {
91
        $error = sprintf('Error N: %s, Description: %s', $this->getErrorCode(), $this->getDescription());
92
93
        if ($return) {
94
            return $error;
95
        }
96
97
        echo $error;
98
99
        return true;
100
    }
101
102
    /**
103
     * Create and return the object of the received result
104
     *
105
     * @param array  $result
106
     * @param string $bot_username
107
     *
108
     * @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
109
     */
110 5
    private function createResultObject(array $result, $bot_username)
111
    {
112 5
        $action = Request::getCurrentAction();
113
114
        // We don't need to save the raw_data of the response object!
115 5
        $result['raw_data'] = null;
116
117
        $result_object_types = [
118 5
            'getChat'              => Chat::class,
119
            'getChatMember'        => ChatMember::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
        $object_class = array_key_exists($action, $result_object_types) ? $result_object_types[$action] : Message::class;
128
129 5
        return new $object_class($result, $bot_username);
130
    }
131
132
    /**
133
     * Create and return the objects array of the received result
134
     *
135
     * @param array  $result
136
     * @param string $bot_username
137
     *
138
     * @return \Longman\TelegramBot\Entities\ChatMember[]|\Longman\TelegramBot\Entities\Games\GameHighScore[]|\Longman\TelegramBot\Entities\Message[]|\Longman\TelegramBot\Entities\Update[]
139
     */
140 2
    private function createResultObjects(array $result, $bot_username)
141
    {
142 2
        $results = [];
143 2
        $action  = Request::getCurrentAction();
144
145
        $result_object_types = [
146 2
            '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