10

I am using Slim v3 and the json schema validator by justinrainbow for my API. What I want to do and just can't get to work is:

  • in the middleware: validate incoming json with defaults. this produces a modified object
  • write the modified object back into the request, so that it can be processed by the core controllers

What I am failing at is:

# inside middleware:
$requestbody = $request->getBody();
$requestobject = json_decode($requestbody);
# validation and modification of $requestobject takes place here
$request->getBody()->write(json_encode($requestobject));
$request->reparseBody();
return $next($request, $response);

From that point on, the request body is just null. What am I doing wrong? I am rather certain that there is something wrong with the way I am modifying Slim objects, because it does not work when I manually try $request->getBody()->write('{"some": "content"}') as well.

tscherg
  • 1,032
  • 8
  • 22

2 Answers2

9

The solution was withParsedBody():

# inside middleware:
$requestbody = $request->getBody();
$requestobject = json_decode($requestbody);

# validation and modification of $requestobject takes place here

$request = $request->withParsedBody($requestobject);
return $next($request, $response);

It completely overwrites the request body with the modified object, just as I needed. What you have to pay mind to:

  • From there on, the request will hold a parsed object as body and on calling $request->getParsedBody() it won't be reparsed, if I understand the source correctly
  • on calling $request->getParsedBody() you usually get an associative array if the body was JSON, but using the snippet above, the parsed body will be an object instead.

May the snippet be helpful to users in the future.

tscherg
  • 1,032
  • 8
  • 22
0

You code replaces the body of the request with the new Data, You must create a new request Contain the previous body with the new data

You can use withAttribute method to pass parameters to the internal routes form the middleware You code will be like that

# inside middleware:
$requestbody = $request->getBody();
$requestobject = json_decode($requestbody);
# validation and modification of $requestobject takes place here
$request=$request->withAttribute(Your Key-Values parms );
return $next($request, $response);
Ramy hakam
  • 522
  • 1
  • 6
  • 19