Get data on a PUT route using silex

0

I would like to know how you can get data passed to a put route using silex. For example:

$app->put('foo/{id}', function(Request $request, $id) use ($app){
  return var_dump($request->get('bar')); //return null 
});

This returns NULL , does anyone know a way to get the data passed by the request?

    
asked by anonymous 28.04.2015 / 13:37

1 answer

1

According to the Silex documentation , you have to instruct your application to accept a request via JSON:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;

$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 : array());
    }
});

Edit: Here is a working example:

<?php

require_once __DIR__.'/../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;

$app = new Silex\Application();

$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->put('/foo/{id}', function(Request $request, $id) use($app) {
    var_dump($request->request->all()); die;
});

$app->run();

I used HTTPie to test the request:

$ echo '{ "lala": "lele" }' | http PUT silex.dev/foo/1

Answer:

HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 45
Content-Type: text/html
Date: Tue, 28 Apr 2015 13:46:47 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Unix) PHP/5.5.20
X-Powered-By: PHP/5.5.20

array(1) {
  ["lala"]=>
  string(4) "lele"
}
    
28.04.2015 / 15:08