Test Failed
Push — master ( e47890...96dce3 )
by Jim
03:33
created

IMCloud::getLatestConfigParameters()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.439
c 0
b 0
f 0
cc 5
eloc 18
nc 12
nop 0
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
        if ($this->needRefresh) {
150
            $this->needRefresh = false;
151
            $this->query->setAll($this->getLatestConfigParameters());
152
        }
153
154
        if (count($fields) == 1 && $fields[0] === '*') {
155
            return $this->query->toArray();
156
        }
157
158
        return $this->query->only($fields);
159
    }
160
161
    /**
162
     * Get a full url
163
     *
164
     * @param $uri
165
     * @return string
166
     */
167
    protected function getFullApiUrl($uri)
168
    {
169
        return Str::startsWith($uri, ['http', 'https']) ? $uri : API::BASE_URL . $uri;
170
    }
171
172
    /**
173
     * Check the array data errors, and Throw exception when the contents contains error.
174
     *
175
     * @param array|Collection $contents
176
     *
177
     * @throws HttpException
178
     */
179
    protected function checkAndThrow($contents)
180
    {
181
        if ($contents instanceof Collection) {
182
            $contents = $contents->toArray();
183
        }
184
185
        if (isset($contents['ErrorCode']) && 0 !== $contents['ErrorCode']) {
186
            if (empty($contents['ErrorInfo'])) {
187
                $contents['ErrorInfo'] = 'Unknown';
188
            }
189
            throw new HttpException($contents['ErrorInfo'], $contents['ErrorCode']);
190
        }
191
    }
192
193
    /**
194
     * Initialize query
195
     *
196
     * @param array $items
197
     * @return Collection
198
     * @throws Exceptions\UserSigException
199
     * @throws MissingArgumentsException
200
     */
201
    protected function initializeQuery(array $items = [])
202
    {
203
        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...
204
            $this->query = new Collection($items ?: $this->getLatestConfigParameters());
205
        }
206
207
        return $this->query;
208
    }
209
}
210