Created
May 23, 2012 13:45
-
-
Save m4rw3r/2775309 to your computer and use it in GitHub Desktop.
InjectStack middleware for ChunkedEncoding
This file contains 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 | |
/* | |
* 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