Completed
Push — master ( fec059...b78efe )
by Jim
02:20
created

IMCloud::getLatestQueryString()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 9
nc 4
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: lenovo
5
 * Date: 6/14/2018
6
 * Time: 8:08 PM
7
 */
8
9
namespace TimSDK\Core;
10
11
use TimSDK\Support\Str;
12
use TimSDK\Support\Log;
13
use TimSDK\Support\Arr;
14
use TimSDK\Support\Collection;
15
use TimSDK\Core\Exceptions\HttpException;
16
use TimSDK\Core\Exceptions\MissingArgumentsException;
17
18
class IMCloud extends BaseIMCloud
19
{
20
    /**
21
     * @var Collection
22
     */
23
    protected $query;
24
25
    /**
26
     * @var bool
27
     */
28
    protected $needRefresh = false;
29
30
    /**
31
     * Set on refresh swith
32
     */
33
    public function needRefresh()
34
    {
35
        $this->needRefresh = true;
36
    }
37
38
    /**
39
     * @return bool
40
     */
41
    public function isNeedRefresh()
42
    {
43
        return (bool) $this->needRefresh;
44
    }
45
46
    /**
47
     * Init
48
     *
49
     * @throws MissingArgumentsException
50
     * @throws \TimSDK\Core\Exceptions\UserSigException
51
     */
52
    public function initialize()
53
    {
54
        $this->initializeQuery();
55
    }
56
57
    /**
58
     * Request api
59
     *
60
     * @param       $uri
61
     * @param array $data
62
     * @param array $options
63
     * @return \TimSDK\Foundation\ResponseBag
64
     * @throws \TimSDK\Core\Exceptions\JsonParseException
65
     * @throws \TimSDK\Core\Exceptions\UserSigException
66
     * @throws \TimSDK\Core\Exceptions\HttpException
67
     * @throws \TimSDK\Core\Exceptions\MissingArgumentsException
68
     */
69
    public function handle($uri, $data = [], $options = [])
70
    {
71
        if (empty($data)) {
72
            $data = '{}';
73
        }
74
75
        $response = $this->httpPostJson($uri, $data, array_merge($options, [
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type string; however, parameter $data of TimSDK\Core\BaseIMCloud::httpPostJson() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

75
        $response = $this->httpPostJson($uri, /** @scrutinizer ignore-type */ $data, array_merge($options, [
Loading history...
76
            'query' => $this->getLatestQueryString([
77
                'sdkappid', 'usersig', 'identifier', 'random', 'contenttype'
78
            ])
79
        ]));
80
81
        $this->checkAndThrow($response->getContents());
82
83
        return $response;
84
    }
85
86
    /**
87
     * Generate sig
88
     *
89
     * @param $identifier
90
     * @return string
91
     * @throws \TimSDK\Core\Exceptions\UserSigException
92
     */
93
    public function generateSig($identifier)
94
    {
95
        return $this->app['TLSSig']->genSig($identifier);
96
    }
97
98
    /**
99
     * Get the latest config parameters array
100
     *
101
     * @return array
102
     * @throws Exceptions\UserSigException
103
     * @throws MissingArgumentsException
104
     */
105
    public function getLatestConfigParameters()
106
    {
107
        $data = Arr::only($this->app['config']->all(), [
108
            'app_id',
109
            'identifier',
110
            'private_key',
111
            'public_key',
112
            'random',
113
            'contenttype',
114
        ]);
115
116
        if (!isset($data['random'])) {
117
            $data['random'] = time();
118
        }
119
120
        if (!isset($data['contenttype'])) {
121
            $data['contenttype'] = 'json';
122
        }
123
124
        foreach (['app_id', 'identifier', 'public_key', 'private_key'] as $item) {
125
            if (empty(Arr::get($data, $item, null))) {
126
                Log::debug('IMCloud Query: ', $data);
127
                throw new MissingArgumentsException("Missing $item.");
128
            }
129
        }
130
131
        $data['usersig'] = $this->generateSig($data['identifier']);
132
        $data['sdkappid'] = $data['app_id'];
133
134
        return $data;
135
    }
136
137
    /**
138
     * Get query string array
139
     *
140
     * @param array $fields
141
     * @return array
142
     * @throws Exceptions\UserSigException
143
     * @throws MissingArgumentsException
144
     */
145
    public function getLatestQueryString(array $fields = ['*'])
146
    {
147
        $this->initializeQuery();
148
149
        Log::debug('Is need refresh: ' . ($this->needRefresh ? 'true' : 'false'));
150
151
        if ($this->needRefresh) {
152
            $this->needRefresh = false;
153
            $this->query->setAll($this->getLatestConfigParameters());
154
        }
155
156
        Log::debug('Request query: ', $this->query->toArray());
157
158
        if (count($fields) == 1 && $fields[0] === '*') {
159
            return $this->query->toArray();
160
        }
161
162
        return $this->query->only($fields);
163
    }
164
165
    /**
166
     * Get a full url
167
     *
168
     * @param $uri
169
     * @return string
170
     */
171
    protected function getFullApiUrl($uri)
172
    {
173
        return Str::startsWith($uri, ['http', 'https']) ? $uri : API::BASE_URL . $uri;
174
    }
175
176
    /**
177
     * Check the array data errors, and Throw exception when the contents contains error.
178
     *
179
     * @param array|Collection $contents
180
     *
181
     * @throws HttpException
182
     */
183
    protected function checkAndThrow($contents)
184
    {
185
        if ($contents instanceof Collection) {
186
            $contents = $contents->toArray();
187
        }
188
189
        if (isset($contents['ErrorCode']) && 0 !== $contents['ErrorCode']) {
190
            if (empty($contents['ErrorInfo'])) {
191
                $contents['ErrorInfo'] = 'Unknown';
192
            }
193
            throw new HttpException($contents['ErrorInfo'], $contents['ErrorCode']);
194
        }
195
    }
196
197
    /**
198
     * Initialize query
199
     *
200
     * @param array $items
201
     * @return Collection
202
     * @throws Exceptions\UserSigException
203
     * @throws MissingArgumentsException
204
     */
205
    protected function initializeQuery(array $items = [])
206
    {
207
        if (!$this->query instanceof Collection) {
0 ignored issues
show
introduced by
$this->query is always a sub-type of TimSDK\Support\Collection. If $this->query can have other possible types, add them to src/Core/IMCloud.php:21.
Loading history...
208
            $this->query = new Collection($items ?: $this->getLatestConfigParameters());
209
        }
210
211
        return $this->query;
212
    }
213
}
214