Symony2 Response Object

I’ve been playing a lot with the Silex Microframework these last weeks.
I had to build an API for an existing code.
The result is amazing, Silex let us build our API, write full coverage unitTests in no more than a week.
I will write a dedicated post about Silex later, the subject is now the Response Object of the Symfony2 HttpFoundation Component :

I found a disturbing behaviour in this object :

  • If you do not set a charset to this object => HTTP Content-Type header is marqued  ‘UTF8′ for “text/*” content-type (defaut content-type is text/html).
  • or If you set a charset by defining it yourself in the header => HTTP Content-Type header is marqued as your charset (good)

But, in both case, the Response::getCharset method will return null.

This is disturbing for the Unit Tests.
Actually, the WebTestCase component provided by Silex get the Response object, when testing a route. So when I check the charset, the test fails.

<?php
require_once dirname(__FILE__) . "/Silex/autoload.php";

use SymfonyComponentHttpFoundationResponse;

$app = new SilexApplication();

/**
* Good HTTP response / Good Behavior of Response::getCharset
*/
$app->get('/testpass/', function() use ($app)
  {
    $response = new Response('Hello world');
    $response->headers->set('Content-Type', 'text/plain');
    $response->setCharset('UTF-8');
    return $response;
  }
);

/**
* Good HTTP response / Bad Behavior of Response::getCharset
*/
$app->get('/testfail/', function() use ($app)
  {
    return new Response(
                      'Hello world'
                      , 200
                      , array('Content-Type' => 'text/plain; charset=UTF-8')
                );
  }
);

I’ll try to enhance this behaviour in the next few days.

2 thoughts on “Symony2 Response Object

  1. To have the expected behavior, you can call prepare() on the Response object. It will populate the defaults for the Content-Type and the Charset if not set explicitly.

    • The prepare() method builds headers with Charset and Content-Type if not set explicitely, but it does not populate the charset method attribute, it sets a local var.
      That was what I was explaining ; the resuts is good, but the unit test fails If you do not explicitely set the charset with the setCharset() method.

      The unit test i’m thinking about is asserting that getCharset returns “UTF-8″ when you have set a header with :

      new Response($content, $code, array(‘Content-Type’ => ‘text/plain; charset=UTF-8′));

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>