mirror of
https://github.com/php-curl-class/php-curl-class.git
synced 2026-08-31 04:34:27 +00:00
Add ability to specify a callback for Curl::download()
This commit is contained in:
+19
-3
@@ -150,12 +150,28 @@ class Curl
|
||||
return $this->exec();
|
||||
}
|
||||
|
||||
public function download($url, $filename)
|
||||
public function download($url, $mixed_filename)
|
||||
{
|
||||
$fh = fopen($filename, 'wb');
|
||||
$callback = false;
|
||||
if (is_callable($mixed_filename)) {
|
||||
$callback = $mixed_filename;
|
||||
$fh = tmpfile();
|
||||
} else {
|
||||
$filename = $mixed_filename;
|
||||
$fh = fopen($filename, 'wb');
|
||||
}
|
||||
|
||||
$this->setOpt(CURLOPT_FILE, $fh);
|
||||
$this->get($url);
|
||||
fclose($fh);
|
||||
|
||||
if ($callback) {
|
||||
rewind($fh);
|
||||
$callback($this, $fh);
|
||||
}
|
||||
|
||||
if (is_resource($fh)) {
|
||||
fclose($fh);
|
||||
}
|
||||
|
||||
// Fix "PHP Notice: Use of undefined constant STDOUT" when reading the
|
||||
// PHP script from stdin.
|
||||
|
||||
@@ -468,6 +468,43 @@ class CurlTest extends PHPUnit_Framework_TestCase
|
||||
$this->assertFalse(file_exists($downloaded_file_path));
|
||||
}
|
||||
|
||||
public function testDownloadCallback()
|
||||
{
|
||||
// Upload a file.
|
||||
$upload_file_path = Helper\get_png();
|
||||
$upload_test = new Test();
|
||||
$upload_test->server('upload_response', 'POST', array(
|
||||
'image' => '@' . $upload_file_path,
|
||||
));
|
||||
$uploaded_file_path = $upload_test->curl->response->file_path;
|
||||
|
||||
// Download the file.
|
||||
$callback_called = false;
|
||||
$curl = new Curl();
|
||||
$curl->setHeader('X-DEBUG-TEST', 'download_response');
|
||||
$curl->download(Test::TEST_URL . '?' . http_build_query(array(
|
||||
'file_path' => $uploaded_file_path,
|
||||
)), function($instance, $fh) use (&$callback_called) {
|
||||
$callback_called = true;
|
||||
PHPUnit_Framework_Assert::assertInstanceOf('Curl\Curl', $instance);
|
||||
PHPUnit_Framework_Assert::assertTrue(is_resource($fh));
|
||||
PHPUnit_Framework_Assert::assertEquals('stream', get_resource_type($fh));
|
||||
PHPUnit_Framework_Assert::assertGreaterThan(0, strlen(stream_get_contents($fh)));
|
||||
PHPUnit_Framework_Assert::assertEquals(0, strlen(stream_get_contents($fh)));
|
||||
fclose($fh);
|
||||
});
|
||||
$this->assertTrue($callback_called);
|
||||
|
||||
// Remove server file.
|
||||
$this->assertEquals('true', $upload_test->server('upload_cleanup', 'POST', array(
|
||||
'file_path' => $uploaded_file_path,
|
||||
)));
|
||||
|
||||
unlink($upload_file_path);
|
||||
$this->assertFalse(file_exists($upload_file_path));
|
||||
$this->assertFalse(file_exists($uploaded_file_path));
|
||||
}
|
||||
|
||||
public function testBasicHttpAuth()
|
||||
{
|
||||
$test = new Test();
|
||||
|
||||
Reference in New Issue
Block a user