From eb8b6dcc19ce935757f642ea4fdc2226ca303c49 Mon Sep 17 00:00:00 2001 From: Zach Borboa Date: Tue, 24 Feb 2015 12:56:17 +0700 Subject: [PATCH] Add ability to specify a callback for Curl::download() --- src/Curl/Curl.php | 22 +++++++++++++-- tests/PHPCurlClass/PHPCurlClassTest.php | 37 +++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/Curl/Curl.php b/src/Curl/Curl.php index 60383cb..2bc9b72 100644 --- a/src/Curl/Curl.php +++ b/src/Curl/Curl.php @@ -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. diff --git a/tests/PHPCurlClass/PHPCurlClassTest.php b/tests/PHPCurlClass/PHPCurlClassTest.php index 4eb67c8..4f3e677 100644 --- a/tests/PHPCurlClass/PHPCurlClassTest.php +++ b/tests/PHPCurlClass/PHPCurlClassTest.php @@ -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();