1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Demv\JSend; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Seld\JsonLint\JsonParser; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class ResponseFactory |
10
|
|
|
* @package Demv\JSend |
11
|
|
|
*/ |
12
|
|
|
final class ResponseFactory |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var ResponseFactory |
16
|
|
|
*/ |
17
|
|
|
private static $instance; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* ResponseFactory constructor. |
21
|
|
|
*/ |
22
|
|
|
private function __construct() |
23
|
|
|
{ |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @return ResponseFactory |
28
|
|
|
*/ |
29
|
|
|
public static function instance(): self |
30
|
|
|
{ |
31
|
|
|
if (self::$instance === null) { |
32
|
|
|
self::$instance = new self(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return self::$instance; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param ResponseInterface $response |
40
|
|
|
* |
41
|
|
|
* @return JSendResponseInterface |
42
|
|
|
* @throws \Seld\JsonLint\ParsingException |
43
|
|
|
*/ |
44
|
|
|
public function convert(ResponseInterface $response): JSendResponseInterface |
45
|
|
|
{ |
46
|
|
|
$content = $response->getBody()->getContents(); |
47
|
|
|
|
48
|
|
|
$parser = new JsonParser(); |
49
|
|
|
$result = $parser->parse($content, JsonParser::PARSE_TO_ASSOC | JsonParser::DETECT_KEY_CONFLICTS); |
50
|
|
|
$result['code'] = $response->getStatusCode(); |
51
|
|
|
|
52
|
|
|
return JSend::interpret($result); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param array|null $data |
57
|
|
|
* |
58
|
|
|
* @return JSendResponseInterface |
59
|
|
|
*/ |
60
|
|
|
public function success(array $data = null): JSendResponseInterface |
61
|
|
|
{ |
62
|
|
|
return new JSendResponse(Status::success(), $data); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param array|null $data |
67
|
|
|
* |
68
|
|
|
* @return JSendResponseInterface |
69
|
|
|
*/ |
70
|
|
|
public function fail(array $data = null): JSendResponseInterface |
71
|
|
|
{ |
72
|
|
|
return new JSendResponse(Status::fail(), $data); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param array $response |
77
|
|
|
* @param int|null $code |
78
|
|
|
* |
79
|
|
|
* @return JSendResponseInterface |
80
|
|
|
*/ |
81
|
|
|
public function error(array $response, int $code = null): JSendResponseInterface |
82
|
|
|
{ |
83
|
|
|
if ($code !== null || !array_key_exists('code', $response)) { |
84
|
|
|
$response['code'] = $code; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return new JSendErrorResponse(Status::error(), $response); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|