Skip to content

Instantly share code, notes, and snippets.

@jonathansanchez
Last active September 9, 2019 12:26
Show Gist options
  • Save jonathansanchez/ee0a13505dd8d63e90bdeb2be184f1c8 to your computer and use it in GitHub Desktop.
Save jonathansanchez/ee0a13505dd8d63e90bdeb2be184f1c8 to your computer and use it in GitHub Desktop.
Receive post json from request on silex
curl http://127.0.0.1:8080/api/v1/test -d '{"type":"limit","event":"incident"}' -H 'Content-Type: application/json'
<?php
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
$app->before(function (Request $request) {
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : []);
}
});
$app->post('/api/v1/test', 'test.controller:index');
$app->error(function (\Exception $e) use ($app) {
return new JsonResponse($e->getMessage());
});
<?php
final class TestController extends SomeBaseController
{
private $someService;
public function __construct(SomeService $someService)
{
parent::__construct($someService);
$this->someService = $someService;
}
public function test(Request $request): JsonResponse
{
$type = $request->request->get('type');
$event = $request->request->get('event');
//Now you can manipulate this vars.
$this
->someService
->execute($type, $event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment