1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-24 18:13:00 +01:00

Allowing a filename to be passed into $request->setResponseBody()

This commit is contained in:
Michael Dowling 2012-12-10 16:51:40 -08:00
parent 09c2a09584
commit 8206dbcbfe
3 changed files with 33 additions and 5 deletions

View File

@ -5,6 +5,7 @@ namespace Guzzle\Http\Message;
use Guzzle\Common\Event;
use Guzzle\Common\Collection;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Utils;
use Guzzle\Http\Exception\RequestException;
use Guzzle\Http\Exception\BadResponseException;
@ -542,9 +543,16 @@ class Request extends AbstractMessage implements RequestInterface
/**
* {@inheritdoc}
*/
public function setResponseBody(EntityBodyInterface $body)
public function setResponseBody($body)
{
$this->responseBody = $body;
// Attempt to open a file for writing if a string was passed
if (is_string($body)) {
if (!($body = fopen($body, 'w+'))) {
throw new InvalidArgumentException('Could not open ' . $body . ' for writing');
}
}
$this->responseBody = EntityBody::factory($body);
return $this;
}

View File

@ -261,11 +261,11 @@ interface RequestInterface extends MessageInterface, HasDispatcherInterface
* This method should be invoked when you need to send the response's entity body somewhere other than the normal
* php://temp buffer. For example, you can send the entity body to a socket, file, or some other custom stream.
*
* @param EntityBodyInterface $body Response body object
*
* @param EntityBodyInterface|string|resource $body Response body object. Pass a string to attempt to store the
* response body in a local file.
* @return Request
*/
public function setResponseBody(EntityBodyInterface $body);
public function setResponseBody($body);
/**
* Determine if the response body is repeatable (readable + seekable)

View File

@ -862,4 +862,24 @@ class RequestTest extends \Guzzle\Tests\GuzzleTestCase
$this->assertEquals(3, (string) $requests[0]->getHeader('Content-Length'));
$this->assertEquals('foo', (string) $requests[0]->getBody());
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testEnsuresFileCanBeCreated()
{
$this->getServer()->flush();
$this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest");
$this->client->get('/')->setResponseBody('/wefwefefefefwewefwe/wefwefwefefwe/wefwefewfw.txt')->send();
}
public function testAllowsFilenameForDownloadingContent()
{
$this->getServer()->flush();
$this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest");
$name = sys_get_temp_dir() . '/foo.txt';
$this->client->get('/')->setResponseBody($name)->send();
$this->assertEquals('test', file_get_contents($name));
unlink($name);
}
}