向PHP Slim 3响应添加状态

时间:2017-02-02 00:33:49

标签: php json routing slim middleware

我在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" } }

1 个答案:

答案 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);
});