Completed
Push — master ( 1785d9...8d1ed5 )
by Armando
03:46
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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 10
    public function __construct(array $data, $bot_username)
35
    {
36
        // Make sure we don't double-save the raw_data
37 10
        unset($data['raw_data']);
38 10
        $data['raw_data'] = $data;
39
40 10
        $is_ok  = isset($data['ok']) ? (bool) $data['ok'] : false;
41 10
        $result = isset($data['result']) ? $data['result'] : null;
42
43 10
        if ($is_ok && is_array($result)) {
44 7
            if ($this->isAssoc($result)) {
45 5
                $data['result'] = $this->createResultObject($result, $bot_username);
46
            } else {
47 2
                $data['result'] = $this->createResultObjects($result, $bot_username);
48
            }
49
        }
50
51 10
        parent::__construct($data, $bot_username);
52 10
    }
53
54
    /**
55
     * Check if array is associative
56
     *
57
     * @link https://stackoverflow.com/a/4254008
58
     *
59
     * @param array $array
60
     *
61
     * @return bool
62
     */
63 7
    protected function isAssoc(array $array)
64
    {
65 7
        return count(array_filter(array_keys($array), 'is_string')) > 0;
66
    }
67
68
    /**
69
     * If response is ok
70
     *
71
     * @return bool
72
     */
73 5
    public function isOk()
74
    {
75 5
        return (bool) $this->getOk();
76
    }
77
78
    /**
79
     * Print error
80
     *
81
     * @see https://secure.php.net/manual/en/function.print-r.php
82
     *
83
     * @param bool $return
84
     *
85
     * @return bool|string
86
     */
87
    public function printError($return = false)
88
    {
89
        $error = sprintf('Error N: %s, Description: %s', $this->getErrorCode(), $this->getDescription());
90
91
        if ($return) {
92
            return $error;
93
        }
94
95
        echo $error;
96
97
        return true;
98
    }
99
100
    /**
101
     * Create and return the object of the received result
102
     *
103
     * @param array  $result
104
     * @param string $bot_username
105
     *
106
     * @return Chat|ChatMember|File|Message|User|UserProfilePhotos|WebhookInfo
107
     */
108 5
    private function createResultObject(array $result, $bot_username)
109
    {
110 5
        $action = Request::getCurrentAction();
111
112
        // We don't need to save the raw_data of the response object!
113 5
        $result['raw_data'] = null;
114
115
        $result_object_types = [
116 5
            'getChat'              => Chat::class,
117
            'getChatMember'        => ChatMember::class,
118
            'getFile'              => File::class,
119
            'getMe'                => User::class,
120
            'getStickerSet'        => StickerSet::class,
121
            'getUserProfilePhotos' => UserProfilePhotos::class,
122
            'getWebhookInfo'       => WebhookInfo::class,
123
        ];
124
125 5
        $object_class = array_key_exists($action, $result_object_types) ? $result_object_types[$action] : Message::class;
126
127 5
        return new $object_class($result, $bot_username);
128
    }
129
130
    /**
131
     * Create and return the objects array of the received result
132
     *
133
     * @param array  $result
134
     * @param string $bot_username
135
     *
136
     * @return ChatMember[]|GameHighScore[]|Message[]|Update[]
137
     */
138 2
    private function createResultObjects(array $result, $bot_username)
139
    {
140 2
        $results = [];
141 2
        $action  = Request::getCurrentAction();
142
143
        $result_object_types = [
144 2
            'getChatAdministrators' => ChatMember::class,
145
            'getGameHighScores'     => GameHighScore::class,
146
            'sendMediaGroup'        => Message::class,
147
        ];
148
149 2
        $object_class = array_key_exists($action, $result_object_types) ? $result_object_types[$action] : Update::class;
150
151 2
        foreach ($result as $data) {
152
            // We don't need to save the raw_data of the response object!
153 1
            $data['raw_data'] = null;
154
155 1
            $results[] = new $object_class($data, $bot_username);
156
        }
157
158 2
        return $results;
159
    }
160
}
161