BaseClient::setFields()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace CloudyCity\TencentMarketingSDK\Kernel;
4
5
use CloudyCity\TencentMarketingSDK\Kernel\Exceptions\ApiException;
6
use CloudyCity\TencentMarketingSDK\Kernel\Exceptions\Exception;
7
use CloudyCity\TencentMarketingSDK\Kernel\Exceptions\InvalidActionException;
8
use CloudyCity\TencentMarketingSDK\Kernel\Exceptions\InvalidResourceException;
9
use CloudyCity\TencentMarketingSDK\Kernel\Http\Parameters\Params;
10
use CloudyCity\TencentMarketingSDK\Kernel\Traits\HasHttpRequests;
11
use CloudyCity\TencentMarketingSDK\Kernel\Traits\HasSdkBaseInfo;
12
use CloudyCity\TencentMarketingSDK\Resources;
13
14
class BaseClient
15
{
16
    use HasHttpRequests, HasSdkBaseInfo {
17
        request as performRequest;
18
        HasHttpRequests::getResponseType insteadof HasSdkBaseInfo;
19
        HasHttpRequests::setResponseType insteadof HasSdkBaseInfo;
20
    }
21
22
    /**
23
     * The base url of official environmental.
24
     *
25
     * @var string
26
     */
27
    protected $baseUrl = 'https://api.e.qq.com';
28
29
    /**
30
     * The base url of sandbox environmental.
31
     *
32
     * @var string
33
     */
34
    protected $sandboxBaseUrl = 'https://sandbox-api.e.qq.com';
35
36
    /**
37
     * The version of API.
38
     *
39
     * @var string
40
     */
41
    protected $version = 'v1.1';
42
43
    /**
44
     * Whether it is a sandbox environment.
45
     *
46
     * @var bool
47
     */
48
    protected $sandbox = false;
49
50
    /**
51
     * Resource.
52
     *
53
     * @var string
54
     */
55
    protected $resource;
56
57
    /**
58
     * Fields.
59
     *
60
     * @var array
61
     */
62
    protected $fields = [];
63
64
    /**
65
     * Client constructor.
66
     *
67
     * @param $advertiserId
68
     * @param $accessToken
69
     * @param string $responseType
70
     */
71
    public function __construct($advertiserId, $accessToken, $responseType = 'array')
72
    {
73
        $this->setAdvertiserId($advertiserId);
74
        $this->setAccessToken($accessToken);
75
        $this->setResponseType($responseType);
76
    }
77
78
    /**
79
     * Set Fields.
80
     *
81
     * @param array $fields
82
     *
83
     * @return $this
84
     */
85
    public function setFields(array $fields)
86
    {
87
        $this->fields = $fields;
88
89
        return $this;
90
    }
91
92
    /**
93
     * Get fields.
94
     *
95
     * @return array
96
     */
97
    public function getFields()
98
    {
99
        return $this->fields;
100
    }
101
102
    /**
103
     * Set env.
104
     *
105
     * @param bool $sandbox
106
     *
107
     * @return $this
108
     */
109
    public function setSandbox($sandbox = true)
110
    {
111
        $this->sandbox = boolval($sandbox);
112
113
        return $this;
114
    }
115
116
    /**
117
     * Set version.
118
     *
119
     * @param $version
120
     *
121
     * @return $this
122
     */
123
    public function setVersion($version)
124
    {
125
        $this->version = $version;
126
127
        return $this;
128
    }
129
130
    /**
131
     * Get Version.
132
     *
133
     * @return string
134
     */
135
    public function getVersion()
136
    {
137
        return $this->version;
138
    }
139
140
    /**
141
     * Whether it is a sandbox environment.
142
     *
143
     * @return bool
144
     */
145
    public function isSandbox()
146
    {
147
        return $this->sandbox;
148
    }
149
150
    /**
151
     * Get base url for request.
152
     *
153
     * @return string
154
     */
155
    public function getBaseUrl()
156
    {
157
        return $this->isSandbox() ? $this->sandboxBaseUrl : $this->baseUrl;
158
    }
159
160
    /**
161
     * Set resource name.
162
     *
163
     * @param $resource
164
     * @param bool $checkValid
165
     *
166
     * @throws InvalidResourceException
167
     *
168
     * @return $this
169
     */
170
    public function setResource($resource, $checkValid = true)
171
    {
172
        if ($checkValid && !Resources::checkResource($resource)) {
173
            throw new InvalidResourceException('Invalid resource:'.$resource);
174
        }
175
176
        $this->resource = $resource;
177
178
        return $this;
179
    }
180
181
    /**
182
     * Get resource name.
183
     *
184
     * @return string
185
     */
186
    public function getResource()
187
    {
188
        return $this->resource;
189
    }
190
191
    /**
192
     * Get url for request.
193
     *
194
     * @param $action
195
     *
196
     * @throws InvalidResourceException
197
     *
198
     * @return string
199
     */
200
    public function getRequestUrl($action)
201
    {
202
        if (!Resources::checkResource($resource = $this->getResource())) {
203
            throw new InvalidResourceException('Invalid resource:'.$resource);
204
        }
205
206
        return sprintf('%s/%s/%s/%s', $this->getBaseUrl(), $this->getVersion(), $resource, $action);
207
    }
208
209
    /**
210
     * Request.
211
     *
212
     * @param $action
213
     * @param array $params
214
     * @param array $headers
215
     * @param bool  $returnRaw
216
     *
217
     * @throws ApiException
218
     * @throws Exception
219
     * @throws Exceptions\InvalidArgumentException
220
     * @throws InvalidActionException
221
     * @throws InvalidResourceException
222
     *
223
     * @return \Psr\Http\Message\ResponseInterface
224
     */
225
    public function request($action, $params = [], $headers = [], $returnRaw = false)
226
    {
227
        if (!$this->checkAction($action)) {
228
            throw new InvalidActionException("resource {$this->getResource()} does not support action:".
229
                "{$action}, please check the official documentation");
230
        }
231
232
        $method = $action === 'get' ? 'get' : 'post';
233
234
        $url = $this->getRequestUrl($action);
235
236
        $options = [
237
            'headers' => $headers,
238
            'query'   => $this->getBaseQuery(),
239
        ];
240
241
        $params = Params::make($params);
242
243
        if ($params->isMultipart()) {
244
            $options['multipart'] = $params->toArray();
245
        } elseif ($method === 'get') {
246
            $options['query'] += $params->toArray();
247
        } else {
248
            $options['form_params'] = $params->toArray();
249
        }
250
251
        $response = $this->performRequest($url, $method, $options);
252
253
        $responseType = $this->getResponseType();
254
255
        $result = $this->castResponseToType($response);
256
        $formatted = $this->castResponseToType($response, $responseType);
257
258
        if (!isset($result['code']) || $result['code'] != 0) {
259
            $message = isset($result['message']) ? $result['message'] : '';
260
            $code = isset($result['code']) ? $result['code'] : 0;
261
262
            throw new ApiException($message, $response, $formatted, $code);
263
        }
264
265
        return $returnRaw ? $response : $this->castResponseToType($response, $responseType);
266
    }
267
268
    /**
269
     * Check Action for resource.
270
     *
271
     * @param $action
272
     *
273
     * @return bool
274
     */
275
    public function checkAction($action)
276
    {
277
        return in_array($action, $this->getValidActions());
278
    }
279
280
    /**
281
     * Get all valid actions for resource.
282
     *
283
     * @return array
284
     */
285
    public function getValidActions()
286
    {
287
        return ['get', 'add', 'update', 'delete'];
288
    }
289
290
    /**
291
     * Get resource.
292
     *
293
     * @param mixed $params
294
     *
295
     * @throws ApiException
296
     * @throws Exception
297
     * @throws Exceptions\InvalidArgumentException
298
     * @throws InvalidActionException
299
     * @throws InvalidResourceException
300
     *
301
     * @return \Psr\Http\Message\ResponseInterface
302
     */
303
    public function get($params = [])
304
    {
305
        return $this->request('get', $params);
306
    }
307
308
    /**
309
     * Add resource.
310
     *
311
     * @param $params
312
     *
313
     * @throws ApiException
314
     * @throws Exception
315
     * @throws Exceptions\InvalidArgumentException
316
     * @throws InvalidActionException
317
     * @throws InvalidResourceException
318
     *
319
     * @return \Psr\Http\Message\ResponseInterface
320
     */
321
    public function add($params)
322
    {
323
        return $this->request('add', $params);
324
    }
325
326
    /**
327
     * Update resource.
328
     *
329
     * @param $params
330
     *
331
     * @throws ApiException
332
     * @throws Exception
333
     * @throws Exceptions\InvalidArgumentException
334
     * @throws InvalidActionException
335
     * @throws InvalidResourceException
336
     *
337
     * @return \Psr\Http\Message\ResponseInterface
338
     */
339
    public function update($params)
340
    {
341
        return $this->request('update', $params);
342
    }
343
344
    /**
345
     * Delete resource.
346
     *
347
     * @param $params
348
     *
349
     * @throws ApiException
350
     * @throws Exception
351
     * @throws Exceptions\InvalidArgumentException
352
     * @throws InvalidActionException
353
     * @throws InvalidResourceException
354
     *
355
     * @return \Psr\Http\Message\ResponseInterface
356
     */
357
    public function delete($params)
358
    {
359
        return $this->request('delete', $params);
360
    }
361
362
    /**
363
     * Get all records by Generator. Each iteration of the loop is a response of singe page.
364
     *
365
     * @param Params $params
366
     * @param int    $pageSize
367
     * @param bool   $throwException
368
     *
369
     * @throws \Exception
370
     *
371
     * @return \Generator
372
     */
373
    public function getAllPages(Params $params = null, $pageSize = 100, $throwException = true)
374
    {
375
        $__params = clone Params::make($params);
376
        $__params->set('page_size', $pageSize);
377
378
        $page = $params->get('page') ?: 1;
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

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

378
        $page = $params->/** @scrutinizer ignore-call */ get('page') ?: 1;

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
379
        $__params->set('page', $page);
380
381
        $totalPage = 1;
382
383
        do {
384
            try {
385
                $result = $this->get($__params);
386
                $data = $this->detectAndCastResponseToType($result, 'collection')->get('data');
387
                $totalPage = $data['page_info']['total_page'];
388
389
                yield $result;
390
            } catch (\Exception $e) {
391
                if (!$throwException) {
392
                    yield $e;
393
                } else {
394
                    throw $e;
395
                }
396
            }
397
398
            $__params->set('page', ++$page);
399
        } while ($page <= $totalPage);
400
    }
401
402
    /**
403
     * Get required auth info for request.
404
     *
405
     * @return array
406
     */
407
    protected function getBaseQuery()
408
    {
409
        return [
410
            'access_token' => $this->getAccessToken(),
411
            'timestamp'    => time(),
412
            'nonce'        => Support\generate_nonce(),
413
            'account_id'   => $this->getAdvertiserId(),
414
        ];
415
    }
416
}
417