|
10 | 10 | use yii\helpers\Json; |
11 | 11 | use yii\helpers\Url; |
12 | 12 | use yii\web\ErrorHandler; |
| 13 | +use yii\web\Link; |
13 | 14 | use yii\web\Response; |
14 | 15 | use yii\web\ResponseFormatterInterface; |
15 | 16 |
|
@@ -53,37 +54,42 @@ class JsonApiResponseFormatter extends Component implements ResponseFormatterInt |
53 | 54 | public function format($response) |
54 | 55 | { |
55 | 56 | $response->getHeaders()->set('Content-Type', 'application/vnd.api+json; charset=UTF-8'); |
56 | | - $apiDocument = [ |
57 | | - 'data' => $response->data, |
58 | | - 'links' => [ |
59 | | - 'self' => Url::current([], true) |
60 | | - ] |
61 | | - ]; |
62 | 57 | $options = $this->encodeOptions; |
63 | 58 | if ($this->prettyPrint) { |
64 | 59 | $options |= JSON_PRETTY_PRINT; |
65 | 60 | } |
66 | | - if ($response->data !== null) { |
67 | | - $apiDocument = $response->data; |
68 | | - if ($response->isClientError || $response->isServerError) { |
69 | | - if (ArrayHelper::isAssociative($response->data)) { |
70 | | - $response->data = [$response->data]; |
71 | | - } |
72 | | - $formattedErrors = []; |
73 | | - foreach ($response->data as $error) { |
74 | | - $formattedError = array_intersect_key($error, array_flip(static::ERROR_ALLOWED_MEMBERS)); |
75 | | - foreach (static::ERROR_EXCEPTION_MAPPING as $member => $key) { |
76 | | - if (isset($error[$key])) { |
77 | | - $formattedError[$member] = (string) $error[$key]; |
78 | | - } |
79 | | - } |
80 | | - if (!empty($formattedError)) { |
81 | | - $formattedErrors[] = $formattedError; |
| 61 | + |
| 62 | + $apiDocument = $response->data; |
| 63 | + |
| 64 | + if (!$response->isEmpty) { |
| 65 | + $apiDocument = ['data' => $response->data]; |
| 66 | + if (\Yii::$app->controller) { |
| 67 | + $apiDocument['links'] = Link::serialize([ |
| 68 | + Link::REL_SELF => Url::current([], true) |
| 69 | + ]); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if ($response->isClientError || $response->isServerError) { |
| 74 | + if (ArrayHelper::isAssociative($response->data)) { |
| 75 | + $response->data = [$response->data]; |
| 76 | + } |
| 77 | + $formattedErrors = []; |
| 78 | + foreach ($response->data as $error) { |
| 79 | + $formattedError = array_intersect_key($error, array_flip(static::ERROR_ALLOWED_MEMBERS)); |
| 80 | + foreach (static::ERROR_EXCEPTION_MAPPING as $member => $key) { |
| 81 | + if (isset($error[$key])) { |
| 82 | + $formattedError[$member] = (string) $error[$key]; |
82 | 83 | } |
83 | 84 | } |
84 | | - $apiDocument = ['errors' => $formattedErrors]; |
| 85 | + if (!empty($formattedError)) { |
| 86 | + $formattedErrors[] = $formattedError; |
| 87 | + } |
85 | 88 | } |
| 89 | + $apiDocument = ['errors' => $formattedErrors]; |
| 90 | + } |
| 91 | + if ($apiDocument !== null) { |
| 92 | + $response->content = Json::encode($apiDocument, $options); |
86 | 93 | } |
87 | | - $response->content = Json::encode($apiDocument, $options); |
88 | 94 | } |
89 | 95 | } |
0 commit comments