Skip to content

Instantly share code, notes, and snippets.

@m4rw3r
Created May 23, 2012 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m4rw3r/2775309 to your computer and use it in GitHub Desktop.
Save m4rw3r/2775309 to your computer and use it in GitHub Desktop.
InjectStack middleware for ChunkedEncoding
<?php
/*
* Created by Martin Wernståhl on 2011-04-25.
* Copyright (c) 2011 Martin Wernståhl.
* All rights reserved.
*/
namespace Inject\Stack\Middleware;
use \Inject\Stack\MiddlewareInterface;
/**
* Applies chunked Transfer-Encoding to "streamed" responses (ie. callbacks),
* interface for using "streamed" responses is still the same.
*/
class ChunkedEncoding implements MiddlewareInterface
{
/**
* The callback for the next middleware or the endpoint in this middleware
* stack.
*
* @var \Inject\Stack\MiddlewareInterface|Closure|ObjectImplementing__invoke
*/
protected $next;
// ------------------------------------------------------------------------
/**
* Tells this middleware which middleware or endpoint it should call if it
* wants the call-chain to proceed.
*
* @param \Inject\Stack\MiddlewareInterface|Closure|ObjectImplementing__invoke
*/
public function setNext($next)
{
$this->next = $next;
}
public function __invoke($env)
{
// Just pass the request through
$callback = $this->next;
$ret = $callback($env);
// If we have a callback, we apply chunked encoding
if( ! empty($ret[2]) && is_callable($ret[2]))
{
$content = $ret[2];
// Wrap the callback in another callback
$ret[2] = function($writer) use($content)
{
// Apply chunked transformations to all the chunks coming through
$chunked_writer = function($string) use($writer)
{
$writer(sprintf('%X', strlen($string))."\r\n".$string."\r\n");
};
$content($chunked_writer);
// Terminate chunked response
$writer("0\r\n\r\n");
};
if(empty($ret[1]['Transfer-Encoding']))
{
$ret[1]['Transfer-Encoding'] = 'chunked';
}
else
{
// Multiple Transfer-Encodings are listed in the order they were applied:
$ret[1]['Transfer-Encoding'] .= "\nchunked";
}
}
return $ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment