Completed
Push — feature/refactor-app-design ( d959a3 )
by Avtandil
03:51
created

ServerResponse::__construct()   C

Complexity

Conditions 8
Paths 36

Size

Total Lines 30
Code Lines 17

Duplication

Lines 7
Ratio 23.33 %

Code Coverage

Tests 15
CRAP Score 8.0155

Importance

Changes 0
Metric Value
dl 7
loc 30
ccs 15
cts 16
cp 0.9375
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 17
nc 36
nop 2
crap 8.0155
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\Http;
10
11
use Longman\TelegramBot\Entities\Chat;
12
use Longman\TelegramBot\Entities\ChatMember;
13
use Longman\TelegramBot\Entities\File;
14
use Longman\TelegramBot\Entities\Message;
15
use Longman\TelegramBot\Entities\Update;
16
use Longman\TelegramBot\Entities\User;
17
use Longman\TelegramBot\Entities\UserProfilePhotos;
18
use Longman\TelegramBot\Entities\WebhookInfo;
19
20
/**
21
 * Class ServerResponse
22
 *
23
 * @link https://core.telegram.org/bots/api#making-requests
24
 *
25
 * @todo method ResponseParameters getParameters()  Field which can help to automatically handle the error
26
 */
27
class ServerResponse
28
{
29
    /**
30
     * ServerResponse constructor.
31
     *
32
     * @param array $data
33
     * @param string $bot_username
34
     *
35
     * @throws \Longman\TelegramBot\Exception\TelegramException
36
     */
37 10
    public function __construct(array $data, $bot_username)
38
    {
39
        // Make sure we don't double-save the raw_data
40 10
        unset($data['raw_data']);
41 10
        $data['raw_data'] = $data;
42
43 10
        $is_ok = isset($data['ok']) ? (bool) $data['ok'] : false;
44 10
        $result = isset($data['result']) ? $data['result'] : null;
45
46 10
        if ($is_ok && is_array($result)) {
47 6
            if ($this->isAssoc($result)) {
48 4
                $data['result'] = $this->createResultObject($result, $bot_username);
49
            } else {
50 2
                $data['result'] = $this->createResultObjects($result, $bot_username);
51
            }
52
        }
53
54
        //Make sure we're not raw_data inception-ing
55 10 View Code Duplication
        if (array_key_exists('raw_data', $data)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56 10
            if ($data['raw_data'] === null) {
57 10
                unset($data['raw_data']);
58
            }
59
        } else {
60
            $data['raw_data'] = $data;
61
        }
62
63 10
        $data['bot_username'] = $bot_username;
64
65 10
        $this->assignMemberVariables($data);
66 10
    }
67
68
    /**
69
     * Helper to set member variables
70
     *
71
     * @param array $data
72
     */
73 10
    protected function assignMemberVariables(array $data)
74
    {
75 10
        foreach ($data as $key => $value) {
76 10
            $this->$key = $value;
77
        }
78 10
    }
79
80
    /**
81
     * Check if array is associative
82
     *
83
     * @link https://stackoverflow.com/a/4254008
84
     *
85
     * @param array $array
86
     *
87
     * @return bool
88
     */
89 6
    protected function isAssoc(array $array)
90
    {
91 6
        return count(array_filter(array_keys($array), 'is_string')) > 0;
92
    }
93
94
    /**
95
     * If response is ok
96
     *
97
     * @return bool
98
     */
99 6
    public function isOk()
100
    {
101 6
        return $this->getOk();
102
    }
103
104
    /**
105
     * If response is ok
106
     *
107
     * @return bool
108
     */
109 6
    public function getOk()
110
    {
111 6
        return isset($this->ok) ? (bool) $this->ok : false;
0 ignored issues
show
Bug introduced by
The property ok does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
112
    }
113
114
    /**
115
     * Return result
116
     *
117
     * @return mixed
118
     */
119 9
    public function getResult()
120
    {
121 9
        return isset($this->result) ? $this->result : null;
0 ignored issues
show
Bug introduced by
The property result does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
122
    }
123
124
    /**
125
     * Return error code
126
     *
127
     * @return int
128
     */
129 5
    public function getErrorCode()
130
    {
131 5
        return isset($this->error_code) ? $this->error_code : null;
0 ignored issues
show
Bug introduced by
The property error_code does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
132
    }
133
134
    /**
135
     * Return human-readable description of the result / unsuccessful request
136
     *
137
     * @return string
138
     */
139 5
    public function getDescription()
140
    {
141 5
        return isset($this->description) ? $this->description : null;
0 ignored issues
show
Bug introduced by
The property description does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
142
    }
143
144
    /**
145
     * Print error
146
     *
147
     * @see https://secure.php.net/manual/en/function.print-r.php
148
     *
149
     * @param bool $return
150
     *
151
     * @return bool|string
152
     */
153
    public function printError($return = false)
154
    {
155
        $error = sprintf('Error N: %s, Description: %s', $this->getErrorCode(), $this->getDescription());
156
157
        if ($return) {
158
            return $error;
159
        }
160
161
        echo $error;
162
163
        return true;
164
    }
165
166
    /**
167
     * Create and return the object of the received result
168
     *
169
     * @param array $result
170
     * @param string $bot_username
171
     *
172
     * @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
173
     * @throws \Longman\TelegramBot\Exception\TelegramException
174
     */
175 4
    private function createResultObject($result, $bot_username)
176
    {
177
        // We don't need to save the raw_data of the response object!
178 4
        $result['raw_data'] = null;
179
180
        $result_object_types = [
181 4
            'total_count' => UserProfilePhotos::class, //Response from getUserProfilePhotos
182
            'file_id'     => File::class,              //Response from getFile
183
            'title'       => Chat::class,              //Response from getChat
184
            'username'    => User::class,              //Response from getMe
185
            'user'        => ChatMember::class,        //Response from getChatMember
186
            'url'         => WebhookInfo::class,       //Response from getWebhookInfo
187
        ];
188 4
        foreach ($result_object_types as $type => $object_class) {
189 4
            if (isset($result[$type])) {
190
191 4
                return new $object_class($result);
192
            }
193
        }
194
195
        //Response from sendMessage
196 2
        return new Message($result, $bot_username);
197
    }
198
199
    /**
200
     * Create and return the objects array of the received result
201
     *
202
     * @param array $result
203
     * @param string $bot_username
204
     *
205
     * @return null|\Longman\TelegramBot\Entities\ChatMember[]|\Longman\TelegramBot\Entities\Update[]
206
     * @throws \Longman\TelegramBot\Exception\TelegramException
207
     */
208 2
    private function createResultObjects($result, $bot_username)
209
    {
210 2
        $results = [];
211 2
        if (isset($result[0]['user'])) {
212
            //Response from getChatAdministrators
213
            foreach ($result as $user) {
214
                // We don't need to save the raw_data of the response object!
215
                $user['raw_data'] = null;
216
217
                $results[] = new ChatMember($user);
218
            }
219
        } else {
220
            //Get Update
221 2
            foreach ($result as $update) {
222
                // We don't need to save the raw_data of the response object!
223 1
                $update['raw_data'] = null;
224
225 1
                $results[] = new Update($update, $bot_username);
226
            }
227
        }
228
229 2
        return $results;
230
    }
231
232
}
233