我在Slim 3中有一块中间件可以验证每条路由的会话。如果验证失败,则返回带有{ 'status' : false, 'error': 'failed validation' }
的JSON对象。如果验证通过,则会将'status' : true
添加到响应JSON对象。
如何将对象属性插入$ response?
$app->add(function($request, $response, $next) {
$valid = doExternalValidation();
if ($valid == false) {
return $response->withJSON(
[ 'status' => false, 'errors' => 'failed validation' ]
);
}
$response = $next($request, $response);
$response->jsonBody['status'] = true; // THIS IS WHAT I WANT TO DO
return $response;
});
$app->get('/test', function ($request, $response, $args) {
$data = [ "foo" => "bar" ];
return $response->withJSON([ 'data' => $data ]);
});
如何更改中间件功能以便获得{ "status" : true, "data" : { "foo" : "bar" } }
?
答案 0 :(得分:2)
<强>解决方案:强>
1)回放Body,就像在中间件的背面一样,正文的光标位于流的末尾
2)解码Body(倒带将光标重置到消息的头部)
3)改变实体
4)使用withJson
5)返回新的Json响应
示例代码:
$app->add(function($request, $response, $next) {
$valid = doExternalValidation();
if ($valid == false) {
return $response->withJSON(
[ 'status' => false, 'errors' => 'failed validation' ]
);
}
$response = $next($request, $response);
$response->getBody()->rewind();
$object = json_decode($response->getBody());
$object['status'] = true;
return $response->withJson($object);
});