Last active
September 9, 2019 12:26
-
-
Save jonathansanchez/ee0a13505dd8d63e90bdeb2be184f1c8 to your computer and use it in GitHub Desktop.
Receive post json from request on silex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
curl http://127.0.0.1:8080/api/v1/test -d '{"type":"limit","event":"incident"}' -H 'Content-Type: application/json' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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