DaitoResponse.php
2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace Daito\Lib;
use RuntimeException;
class DaitoResponse
{
/**
* Build a successful response payload.
*/
public static function success($message = 'Success', array $arrData = array(), $statusCode = 200)
{
return self::make(true, $message, $arrData, $statusCode);
}
/**
* Build a failed response payload.
*/
public static function fail($message = 'Failed', array $arrData = array(), $statusCode = 400)
{
return self::make(false, $message, $arrData, $statusCode);
}
/**
* Build a response payload with a stable structure for all APIs.
*/
public static function make($isSuccess, $message, array $arrData = array(), $statusCode = 200)
{
return array_merge(array(
'success' => $isSuccess ? 1 : 0,
'message' => (string) $message,
'status_code' => (int) $statusCode,
), $arrData);
}
/**
* Convert payload array to JSON.
*/
public static function toJson(array $arrPayload)
{
$json = json_encode($arrPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($json === false) {
throw new RuntimeException('Can not encode response payload to JSON.');
}
return $json;
}
/**
* Create success payload and return JSON string.
*/
public static function successJson($message = 'Success', array $arrData = array(), $statusCode = 200)
{
return self::toJson(self::success($message, $arrData, $statusCode));
}
/**
* Create failed payload and return JSON string.
*/
public static function failJson($message = 'Failed', array $arrData = array(), $statusCode = 400)
{
return self::toJson(self::fail($message, $arrData, $statusCode));
}
/**
* Build a validation failed payload with HTTP 422 default.
*/
public static function validateFail(array $arrErrors, $message = 'Validation failed', $statusCode = 422)
{
return self::fail(
$message,
array(
'errors' => $arrErrors,
),
$statusCode
);
}
/**
* Build a validation failed payload and return JSON string.
*/
public static function validateFailJson(array $arrErrors, $message = 'Validation failed', $statusCode = 422)
{
return self::toJson(self::validateFail($arrErrors, $message, $statusCode));
}
}