phproutesrequestthephpleague

Capture incoming request data


I have been experimenting with the current version of the wonderful package for routing from thephpleague.

I have a simple index page to handle the routing and it works just fine.

<?php declare(strict_types=1);

use Laminas\Diactoros\ServerRequestFactory;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Laminas\Diactoros\ResponseFactory;
use League\Route\Router;
use League\Route\Strategy\JsonStrategy;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

$strategy = new JsonStrategy(new ResponseFactory());
$router = new Router;
$router->setStrategy($strategy);

$router->post(
    '/hello',
    function (ServerRequestInterface $request): ResponseInterface
    {
        var_dump($request->getParsedBody());
    }
);

$request = ServerRequestFactory::fromGlobals(
    $_SERVER,
    $_GET,
    $_POST,
    $_COOKIE,
    $_FILES
);
$response = $router->dispatch($request);

// send the response to the browser
(new SapiEmitter)->emit($response);

My problem is when I send a POST request with JSON data in it, I am unable to capture it in my code as indicated by the line var_dump($request->getParsedBody());.

At the moment, the only way I am able to capture the data sent with the request is by running json_decode(file_get_contents('php://input'), true);.

What I do need to do in order to get the payload sent with whatever request, be it GET, POST, PUT, PATCH, or otherwise?

Thank you.


Solution

  • I finally figured it out. After close examination, I think using dependency injection, ServerRequestInterface is mapped to Laminas\Diactoros\ServerRequest.

    So, to illustrate

    $router->post(
        '/hello',
        function (ServerRequestInterface $request): ResponseInterface {
            var_dump(
                $request->getHeaders(),
                $request->getParsedBody(),
                $request->getQueryParams(),
                $request->getUploadedFiles(),
                $request->getBody()->getContents(),
                $request // Laminas\Diactoros\ServerRequest
            );
        }
    );
    

    where

    1. $request->getHeaders() gives you the request headers
    2. $request->getParsedBody() will return to all the data as an array sent through when the header Content-Type: multipart/form-data is set (at least as far as I have experimented)
    3. $request->getQueryParams() gives all the query string params as an array just like $_GET
    4. $request->getUploadedFiles() gives all the the uploaded files as an array of instances of Laminas\Diactoros\UploadedFile
    5. $request->getBody()->getContents() will return to all data the as a string when the header Content-Type: application/json is set. You can then run json_decode($request->getBody()->getContents(), true) to get the actual contents an array