[HttpFoundation] added Request::__toString()

This commit is contained in:
Fabien Potencier 2011-05-15 12:33:06 +02:00
parent 62d09b8fb2
commit dcb4ef6e23
2 changed files with 33 additions and 4 deletions

View File

@ -165,6 +165,7 @@ class Request
'REMOTE_ADDR' => '127.0.0.1', 'REMOTE_ADDR' => '127.0.0.1',
'SCRIPT_NAME' => '', 'SCRIPT_NAME' => '',
'SCRIPT_FILENAME' => '', 'SCRIPT_FILENAME' => '',
'SERVER_PROTOCOL' => 'HTTP/1.1',
); );
$components = parse_url($uri); $components = parse_url($uri);
@ -280,6 +281,32 @@ class Request
$this->headers = clone $this->headers; $this->headers = clone $this->headers;
} }
/**
* Returns the request as a string.
*
* @return string The request
*/
public function __toString()
{
// status
$content = sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n";
$beautifier = function ($name) {
return preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", ucfirst($name));
};
// headers
foreach ($this->headers->all() as $name => $values) {
foreach ($values as $value) {
$content .= sprintf("%s: %s\r\n", $beautifier($name), $value);
}
}
$content .= "\r\n".$this->getContent();
return $content;
}
/** /**
* Overrides the PHP global variables according to this request instance. * Overrides the PHP global variables according to this request instance.
* *

View File

@ -96,17 +96,19 @@ class Response
*/ */
public function __toString() public function __toString()
{ {
$content = '';
$this->fixContentType(); $this->fixContentType();
// status // status
$content .= sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n"; $content = sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n";
$beautifier = function ($name) {
return preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", ucfirst($name));
};
// headers // headers
foreach ($this->headers->all() as $name => $values) { foreach ($this->headers->all() as $name => $values) {
foreach ($values as $value) { foreach ($values as $value) {
$content .= "$name: $value\r\n"; $content .= sprintf("%s: %s\r\n", $beautifier($name), $value);
} }
} }