Skip to content

Instantly share code, notes, and snippets.

@gabbydgab
Created August 18, 2016 10:07
Show Gist options
  • Save gabbydgab/0193c4b6a8e02f658e9b5f7b7650235d to your computer and use it in GitHub Desktop.
Save gabbydgab/0193c4b6a8e02f658e9b5f7b7650235d to your computer and use it in GitHub Desktop.
[Zend Expressive] Testing $response->getParsedBody()
// AbstractRestController from https://blog.alejandrocelaya.com/2016/06/24/dispatch-rest-like-requests-with-a-single-controller-class-in-zend-expressive/
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;
use App\Rest\AbstractRestController;
final class MyRestController extends AbstractRestController
{
// GET Method
// URL: localhost/employees
public function get(Request $request, Response $response, callable $out = null)
{
$id = $request->getAttribute(self::IDENTIFIER_NAME); //it returns the expected string
// with some code after
}
// POST Method
// URL: localhost/employees
// Body Params: x-www-form-urlencoded
// id = 1
// name = Joe
public function create(Request $request, Response $response, callable $out = null)
{
$data = $request->getParsedBody();
var_dump($data); //it returns the expected array ['id'= 1, 'name' = 'Joe']
}
// PUT Method
// URL: localhost/employees/1
// Body Params: x-www-form-urlencoded
// id = 1
// name = Joey
public function update(Request $request, Response $response, callable $out = null)
{
$data = $request->getParsedBody();
var_dump($data); // returns empty array
$content = $request->getBody()->getContents();
var_dump($content); // returns string 'id=1&name=joey'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment