IMCloud::getLatestConfigParameters()   A
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
nc 12
nop 0
dl 0
loc 31
ccs 14
cts 14
cp 1
crap 5
rs 9.1128
c 0
b 0
f 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 2
    public function needRefresh()
34
    {
35 2
        $this->needRefresh = true;
36 2
    }
37
38
    /**
39
     * @return bool
40
     */
41 1
    public function isNeedRefresh()
42
    {
43 1
        return (bool) $this->needRefresh;
44
    }
45
46
    /**
47
     * Init
48
     *
49
     * @throws MissingArgumentsException
50
     * @throws \TimSDK\Core\Exceptions\UserSigException
51
     */
52 6
    public function initialize()
53
    {
54 6
        $this->initializeQuery();
55 2
    }
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 1
    public function handle($uri, $data = [], $options = [])
70
    {
71 1
        if (empty($data)) {
72 1
            $data = '{}';
73
        }
74
75 1
        $response = $this->httpPostJson($uri, $data, array_merge($options, [
0 ignored issues
show
Bug introduced by
It seems like $data defined by '{}' on line 72 can also be of type string; however, TimSDK\Core\BaseIMCloud::httpPostJson() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
76 1
            'query' => $this->getLatestQueryString([
77 1
                'sdkappid', 'usersig', 'identifier', 'random', 'contenttype'
78
            ])
79
        ]));
80
81 1
        $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 2
    public function generateSig($identifier)
94
    {
95 2
        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 6
    public function getLatestConfigParameters()
106
    {
107 6
        $data = Arr::only($this->app['config']->all(), [
108 6
            'app_id',
109
            'identifier',
110
            'private_key',
111
            'public_key',
112
            'random',
113
            'contenttype',
114
        ]);
115
116 6
        if (!isset($data['random'])) {
117 6
            $data['random'] = time();
118
        }
119
120 6
        if (!isset($data['contenttype'])) {
121 6
            $data['contenttype'] = 'json';
122
        }
123
124 6
        foreach (['app_id', 'identifier', 'public_key', 'private_key'] as $item) {
125 6
            if (empty(Arr::get($data, $item, null))) {
126 4
                Log::debug('IMCloud Query: ', $data);
127 6
                throw new MissingArgumentsException("Missing $item.");
128
            }
129
        }
130
131 2
        $data['usersig'] = $this->generateSig($data['identifier']);
132 2
        $data['sdkappid'] = $data['app_id'];
133
134 2
        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 2
    public function getLatestQueryString(array $fields = ['*'])
146
    {
147 2
        $this->initializeQuery();
148
149 2
        Log::debug('Is need refresh: ' . ($this->needRefresh ? 'true' : 'false'));
150
151 2
        if ($this->needRefresh) {
152 2
            $this->needRefresh = false;
153 2
            $this->query->setAll($this->getLatestConfigParameters());
154
        }
155
156 2
        Log::debug('Request query: ', $this->query->toArray());
157
158 2
        if (count($fields) == 1 && $fields[0] === '*') {
159 2
            return $this->query->toArray();
160
        }
161
162 1
        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 1
    protected function checkAndThrow($contents)
184
    {
185 1
        if ($contents instanceof Collection) {
186 1
            $contents = $contents->toArray();
187
        }
188
189 1
        if (isset($contents['ErrorCode']) && 0 !== $contents['ErrorCode']) {
190 1
            if (empty($contents['ErrorInfo'])) {
191
                $contents['ErrorInfo'] = 'Unknown';
192
            }
193 1
            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 6
    protected function initializeQuery(array $items = [])
206
    {
207 6
        if (!$this->query instanceof Collection) {
208 6
            $this->query = new Collection($items ?: $this->getLatestConfigParameters());
209
        }
210
211 2
        return $this->query;
212
    }
213
}
214