3

I've read the Bundle documentation (FOS rest-bundle), and can't find anything on compressing a response, and I'm unable to set compression to happen at the web-server level.

Is there a way to make the bundle return a gzip(or deflate) compressed response?

My current thinking it to implement a response listener, catch it and compress it but I feel like there's likely an existing way out there.

Edit

I was unable to find anything in FOS Rest Bundle that enabled this - most likely they expect it to be done at the server level. The solution was to create an Event Subscriber:

public function getSubscribedEvents() {
    return [KernelEvents::RESPONSE => ['compressResponse', -256]];
}

Within my compress response method I'm using deflate on the body content and adding the proper content-encoding header:

public function compressResponse(FilterResponseEvent $event)
{
    $response = $event->getResponse();

    if ($response->headers->get('content-type') !== 'application/json') {
        return;
    }

    $response->setContent(gzdeflate($response->getContent()));
    $response->headers->set('Content-encoding', 'deflate');
}

This servers our purposes pretty well.

Erik
  • 20,526
  • 8
  • 45
  • 76

1 Answers1

2

We make that happen on Apache Level in order to enable webserver compression for application/json output as well by using the following conf.

Copied from standard deflate conf in PHP buildpack and overwriting it with:

<IfModule filter_module>
   <IfModule deflate_module>
   AddOutputFilterByType DEFLATE application/json text/html text/plain text/xml text/css text/javascript application/javascript
   </IfModule>
</IfModule>

Adding application/json to this conf did the trick for us.

LBA
  • 3,859
  • 2
  • 21
  • 60
  • "I'm unable to set compression to happen at the web-server level". I did not mean I am not able to do so. I meant we are not allowed to. – Erik Oct 01 '18 at 15:48
  • 1
    @Erik, sorry, misunderstood that. Do you think it makes sense to keep this answer in case anyone might require this approach? – LBA Oct 01 '18 at 15:54