Passed
Push — feature/optimize ( 06281d )
by Fu
03:39
created

Response::parseData()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 9
rs 9.6111
c 0
b 0
f 0
cc 5
nc 3
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: frowhy
5
 * Date: 2017/8/1
6
 * Time: 下午3:25
7
 */
8
9
namespace Modules\Core\Supports;
10
11
use Asm89\Stack\CorsService;
12
use Illuminate\Contracts\Support\{
13
    Arrayable, Renderable, Responsable
14
};
15
use Illuminate\Http\Response as BaseResponse;
16
use Illuminate\Support\{Arr, Str};
17
use Modules\Core\Contracts\Support\Boolable;
18
use Modules\Core\Enums\StatusCodeEnum;
19
use SoapBox\Formatter\Formatter;
20
21
class Response implements Responsable, Arrayable, Renderable, Boolable
22
{
23
    protected $response;
24
    protected $statusCode;
25
26
    public function __construct(array $response)
27
    {
28
        $this->response = $response;
29
        $this->statusCode = $response['meta']['status_code'] ?? StatusCodeEnum::HTTP_OK;
30
31
        return $this;
32
    }
33
34
    private static function parseMeta($data)
35
    {
36
        if ((is_array($data) && Arr::has($data, 'meta'))) {
37
            return Arr::get($data, 'meta');
38
        } else {
39
            return [];
40
        }
41
    }
42
43
    private static function parseData($data)
44
    {
45
        if (is_array($data) && Arr::has($data, 'data')) {
46
            return Arr::get($data, 'data');
47
        } else {
48
            if (is_string($data) && json_decode($data)) {
49
                return json_decode($data);
50
            } else {
51
                return $data;
52
            }
53
        }
54
    }
55
56
    /**
57
     * 格式化响应
58
     *
59
     * @return \Illuminate\Http\Response
60
     */
61
    private function format(): BaseResponse
62
    {
63
        list($response, $statusCode) = [$this->response, $this->statusCode];
64
        $formatter = Formatter::make($response, Formatter::ARR);
65
        $format = self::param('output_format') ?? (config('core.api.output_format'));
66
        $statusCode =
67
            (self::param('status_sync') ?? config('core.api.status_sync')) ? $statusCode : StatusCodeEnum::HTTP_OK;
68
        if (in_array($format, ['application/xml', 'xml'])) {
69
            $response = response($formatter->toXml(), $statusCode, ['Content-Type' => 'application/xml']);
70
        } elseif (in_array($format, ['application/x-yaml', 'yaml'])) {
71
            $response = response($formatter->toYaml(), $statusCode, ['Content-Type' => 'application/x-yaml']);
72
        } elseif (in_array($format, ['text/csv', 'csv'])) {
73
            $response = response($formatter->toCsv(), $statusCode, ['Content-Type' => 'text/csv']);
74
        } elseif (in_array($format, ['application/json', 'json'])) {
75
            $response = response($formatter->toJson(), $statusCode, ['Content-Type' => 'application/json']);
76
        } else {
77
            $response = response($response, $statusCode);
78
        }
79
        return $response;
80
    }
81
82
    /**
83
     * s
84
     * 允许跨域请求
85
     *
86
     * @param \Illuminate\Http\Response $response
87
     * @return \Illuminate\Http\Response
88
     */
89
    private function cors(BaseResponse $response): BaseResponse
90
    {
91
        if (config('core.api.cors_enabled')) {
92
            /** @var CorsService $cors */
93
            $cors = app(CorsService::class);
94
            $request = request();
95
96
            if ($cors->isCorsRequest(request())) {
97
                if (!$response->headers->has('Access-Control-Allow-Origin')) {
98
                    $response = $cors->addActualRequestHeaders($response, $request);
99
                }
100
            }
101
        }
102
103
        return $response;
104
    }
105
106
    /**
107
     * Create an HTTP response that represents the object.
108
     *
109
     * @param \Illuminate\Http\Request $request
110
     *
111
     * @return \Illuminate\Http\Response
112
     */
113
    public function toResponse($request): BaseResponse
114
    {
115
        return $this->render();
116
    }
117
118
    /**
119
     * Get the instance as an array.
120
     *
121
     * @return array
122
     */
123
    public function toArray(): array
124
    {
125
        return (array) Arr::get($this->response, 'data');
126
    }
127
128
    /**
129
     * Get the evaluated contents of the object.
130
     *
131
     * @return \Illuminate\Http\Response
132
     */
133
    public function render(): BaseResponse
134
    {
135
        return $this->cors($this->format());
136
    }
137
138
    /**
139
     * Get the true and false of the instance.
140
     *
141
     * @return bool
142
     */
143
    public function toBool(): bool
144
    {
145
        return Str::startsWith(Arr::get($this->response, 'meta.status_code'), 2);
146
    }
147
148
    public static function param(string $param)
149
    {
150
        $request = app('Illuminate\Http\Request');
151
        if ($request->has($param)) {
152
            return $request->get($param);
153
        } else {
154
            $header_param = Str::title(Str::kebab(Str::studly($param)));
155
            if ($request->hasHeader($header_param)) {
156
                return $request->header($header_param);
157
            }
158
        }
159
160
        return null;
161
    }
162
163
    /**
164
     * Return an response.
165
     *
166
     * @param array $response
167
     *
168
     * @return Response
169
     */
170
    private static function call(array $response): Response
171
    {
172
        return new self($response);
173
    }
174
175
    /**
176
     * Response Handle
177
     *
178
     * @param int $statusCode
179
     * @param $data
180
     * @param bool $overwrite
181
     * @param string|null $message
182
     * @return \Modules\Core\Supports\Response
183
     */
184
    public static function handle(
185
        int $statusCode,
186
        $data = null,
187
        bool $overwrite = false,
188
        string $message = null
189
    ): Response {
190
        if (($overwrite && is_array($data))) {
191
            $_data = $data;
192
        } else {
193
            $_data = self::parseData($data);
194
        }
195
196
        $_meta = self::parseMeta($data);
197
198
        $_meta = Arr::prepend($_meta, $statusCode, 'status_code');
199
        $_meta = Arr::prepend($_meta, $message ?? StatusCodeEnum::__($statusCode), 'message');
200
201
        Arr::set($response, 'meta', $_meta);
202
203
        if (!is_null($_data)) {
204
            Arr::set($response, 'data', $_data);
205
        }
206
207
        return self::call($response);
208
    }
209
210
    /**
211
     * Response Ok
212
     *
213
     * @param $data
214
     * @param bool $overwrite
215
     * @param string|null $message
216
     * @return \Modules\Core\Supports\Response
217
     */
218
    public static function handleOk($data = null, bool $overwrite = false, string $message = null): Response
219
    {
220
        return self::handle(StatusCodeEnum::HTTP_OK, $data, $overwrite, $message);
221
    }
222
223
    /**
224
     * Response Created
225
     *
226
     * @param $data
227
     * @param bool $overwrite
228
     * @param string|null $message
229
     * @return \Modules\Core\Supports\Response
230
     */
231
    public static function handleCreated($data = null, bool $overwrite = false, string $message = null): Response
232
    {
233
        return self::handle(StatusCodeEnum::HTTP_CREATED, $data, $overwrite, $message);
234
    }
235
236
    /**
237
     * Response Accepted
238
     *
239
     * @param $data
240
     * @param bool $overwrite
241
     * @param string|null $message
242
     * @return \Modules\Core\Supports\Response
243
     */
244
    public static function handleAccepted($data = null, bool $overwrite = false, string $message = null): Response
245
    {
246
        return self::handle(StatusCodeEnum::HTTP_ACCEPTED, $data, $overwrite, $message);
247
    }
248
249
    /**
250
     * Response NoContent
251
     *
252
     * @param $data
253
     * @param bool $overwrite
254
     * @param string|null $message
255
     * @return \Modules\Core\Supports\Response
256
     */
257
    public static function handleNoContent($data = null, bool $overwrite = false, string $message = null): Response
258
    {
259
        return self::handle(StatusCodeEnum::HTTP_NO_CONTENT, $data, $overwrite, $message);
260
    }
261
262
    /**
263
     * Response ResetContent
264
     *
265
     * @param $data
266
     * @param bool $overwrite
267
     * @param string|null $message
268
     * @return \Modules\Core\Supports\Response
269
     */
270
    public static function handleResetContent($data = null, bool $overwrite = false, string $message = null): Response
271
    {
272
        return self::handle(StatusCodeEnum::HTTP_RESET_CONTENT, $data, $overwrite, $message);
273
    }
274
275
    /**
276
     * Response SeeOther
277
     *
278
     * @param $data
279
     * @param bool $overwrite
280
     * @param string|null $message
281
     * @return \Modules\Core\Supports\Response
282
     */
283
    public static function handleSeeOther($data = null, bool $overwrite = false, string $message = null): Response
284
    {
285
        return self::handle(StatusCodeEnum::HTTP_SEE_OTHER, $data, $overwrite, $message);
286
    }
287
288
    /**
289
     * Response BadRequest
290
     *
291
     * @param $data
292
     * @param bool $overwrite
293
     * @param string|null $message
294
     * @return \Modules\Core\Supports\Response
295
     */
296
    public static function handleBadRequest($data = null, bool $overwrite = false, string $message = null): Response
297
    {
298
        return self::handle(StatusCodeEnum::HTTP_BAD_REQUEST, $data, $overwrite, $message);
299
    }
300
301
    /**
302
     * Response Unauthorized
303
     *
304
     * @param $data
305
     * @param bool $overwrite
306
     * @param string|null $message
307
     * @return \Modules\Core\Supports\Response
308
     */
309
    public static function handleUnauthorized($data = null, bool $overwrite = false, string $message = null): Response
310
    {
311
        return self::handle(StatusCodeEnum::HTTP_UNAUTHORIZED, $data, $overwrite, $message);
312
    }
313
314
    /**
315
     * Response PaymentRequired
316
     *
317
     * @param $data
318
     * @param bool $overwrite
319
     * @param string|null $message
320
     * @return \Modules\Core\Supports\Response
321
     */
322
    public static function handlePaymentRequired(
323
        $data = null,
324
        bool $overwrite = false,
325
        string $message = null
326
    ): Response {
327
        return self::handle(StatusCodeEnum::HTTP_PAYMENT_REQUIRED, $data, $overwrite, $message);
328
    }
329
330
    /**
331
     * Response Forbidden
332
     *
333
     * @param $data
334
     * @param bool $overwrite
335
     * @param string|null $message
336
     * @return \Modules\Core\Supports\Response
337
     */
338
    public static function handleForbidden($data = null, bool $overwrite = false, string $message = null): Response
339
    {
340
        return self::handle(StatusCodeEnum::HTTP_PAYMENT_REQUIRED, $data, $overwrite, $message);
341
    }
342
343
    /**
344
     * Response NotFound
345
     *
346
     * @param $data
347
     * @param bool $overwrite
348
     * @param string|null $message
349
     * @return \Modules\Core\Supports\Response
350
     */
351
    public static function handleNotFound($data = null, bool $overwrite = false, string $message = null): Response
352
    {
353
        return self::handle(StatusCodeEnum::HTTP_NOT_FOUND, $data, $overwrite, $message);
354
    }
355
356
    /**
357
     * Response UnprocessableEntity
358
     *
359
     * @param $data
360
     * @param bool $overwrite
361
     * @param string|null $message
362
     * @return \Modules\Core\Supports\Response
363
     */
364
    public static function handleUnprocessableEntity(
365
        $data = null,
366
        bool $overwrite = false,
367
        string $message = null
368
    ): Response {
369
        return self::handle(StatusCodeEnum::HTTP_UNPROCESSABLE_ENTITY, $data, $overwrite, $message);
370
    }
371
372
    /**
373
     * Response Locked
374
     *
375
     * @param $data
376
     * @param bool $overwrite
377
     * @param string|null $message
378
     * @return \Modules\Core\Supports\Response
379
     */
380
    public static function handleLocked($data = null, bool $overwrite = false, string $message = null): Response
381
    {
382
        return self::handle(StatusCodeEnum::HTTP_LOCKED, $data, $overwrite, $message);
383
    }
384
385
    /**
386
     * Response TooManyRequests
387
     *
388
     * @param $data
389
     * @param bool $overwrite
390
     * @param string|null $message
391
     * @return \Modules\Core\Supports\Response
392
     */
393
    public static function handleTooManyRequests(
394
        $data = null,
395
        bool $overwrite = false,
396
        string $message = null
397
    ): Response {
398
        return self::handle(StatusCodeEnum::HTTP_TOO_MANY_REQUESTS, $data, $overwrite, $message);
399
    }
400
401
    /**
402
     * Response InternalServerError
403
     *
404
     * @param $data
405
     * @param bool $overwrite
406
     * @param string|null $message
407
     * @return \Modules\Core\Supports\Response
408
     */
409
    public static function handleInternalServerError(
410
        $data = null,
411
        bool $overwrite = false,
412
        string $message = null
413
    ): Response {
414
        return self::handle(StatusCodeEnum::HTTP_INTERNAL_SERVER_ERROR, $data, $overwrite, $message);
415
    }
416
417
    /**
418
     * Response NotImplemented
419
     *
420
     * @param $data
421
     * @param bool $overwrite
422
     * @param string|null $message
423
     * @return \Modules\Core\Supports\Response
424
     */
425
    public static function handleNotImplemented($data = null, bool $overwrite = false, string $message = null): Response
426
    {
427
        return self::handle(StatusCodeEnum::HTTP_NOT_IMPLEMENTED, $data, $overwrite, $message);
428
    }
429
}
430