Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"phpunit/phpunit": "^11.5.46",
"psr/log": "^3.0.2",
"yiisoft/files": "^2.1",
"yiisoft/test-support": "^3.1.0"
"yiisoft/test-support": "^3.2.0"
},
"suggest": {
"ext-curl": "To use `CurlTransport`.",
Expand Down
3 changes: 2 additions & 1 deletion infection.json.dist
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
]
},
"logs": {
"text": "php:\/\/stderr",
"text": "runtime/infection/run.log",
"stryker": {
"report": "master"
}
},
"tmpDir": "runtime/infection",
"mutators": {
"@default": true
},
Expand Down
60 changes: 60 additions & 0 deletions src/DownloadedFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

namespace Phptg\BotApi;

/**
* Represents a downloaded file from the Telegram servers.
*
* @api
*/
final readonly class DownloadedFile
{
/**
* @param resource $stream A `php://temp` stream with the file content, rewound to the beginning.
*/
public function __construct(
private mixed $stream,
) {}

/**
* Returns the stream with the file content.
*
* @return resource the stream with the file content (`php://temp` resource).
*/
public function getStream(): mixed
{
return $this->stream;
}

/**
* Saves the file content to the specified path.
*
* @throws SaveFileException If an error occurred while saving the file.
*/
public function saveTo(string $path): void
{
set_error_handler(
static function (int $errorNumber, string $errorString): bool {
throw new SaveFileException($errorString);
},
);
try {
file_put_contents($path, $this->stream);
} finally {
restore_error_handler();
}
}

/**
* Returns the file content as a string.
*/
public function getBody(): string
{
/**
* @var string We expect the stream to be valid, so `stream_get_contents()` returns string.
*/
return stream_get_contents($this->stream);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace Phptg\BotApi\Transport;
namespace Phptg\BotApi;

use RuntimeException;

Expand Down
35 changes: 10 additions & 25 deletions src/TelegramBotApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,6 @@
use Phptg\BotApi\Transport\CurlTransport;
use Phptg\BotApi\Transport\DownloadFileException;
use Phptg\BotApi\Transport\NativeTransport;
use Phptg\BotApi\Transport\SaveFileException;
use Phptg\BotApi\Transport\TransportInterface;
use Phptg\BotApi\Type\AcceptedGiftTypes;
use Phptg\BotApi\Type\BotCommand;
Expand Down Expand Up @@ -310,38 +309,24 @@ public function makeFileUrl(string|File $file): string
}

/**
* Downloads a file from the Telegram servers and returns its content.
* Downloads a file from the Telegram servers.
*
* @param string|File $file File path or {@see File} object.
*
* @return string The file content.
*
* @throws DownloadFileException If an error occurred while downloading the file.
* @throws LogicException If the file path is not specified in `File` object.
*/
public function downloadFile(string|File $file): string
{
return $this->transport->downloadFile(
$this->makeFileUrl($file),
);
}

/**
* Downloads a file from the Telegram servers and saves it to a file.
*
* @param string|File $file File path or {@see File} object.
* @param string $savePath The path to save the file.
*
* @throws DownloadFileException If an error occurred while downloading the file.
* @throws SaveFileException If an error occurred while saving the file.
* @throws LogicException If the file path is not specified in `File` object.
*/
public function downloadFileTo(string|File $file, string $savePath): void
public function downloadFile(string|File $file): DownloadedFile
{
$this->transport->downloadFileTo(
/**
* @var resource $stream `php://temp` always opens successfully.
*/
$stream = fopen('php://temp', 'r+b');
$this->transport->downloadFile(
$this->makeFileUrl($file),
$savePath,
$stream,
);
rewind($stream);
return new DownloadedFile($stream);
}

/**
Expand Down
46 changes: 2 additions & 44 deletions src/Transport/CurlTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,53 +78,11 @@ public function postWithFiles(string $url, array $data, array $files): ApiRespon
return $this->send($options);
}

public function downloadFile(string $url): string
public function downloadFile(string $url, mixed $stream): void
{
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => true,
CURLOPT_SHARE => $this->curlShareHandle,
];

try {
$curl = $this->curl->init();
} catch (CurlException $exception) {
throw new DownloadFileException($exception->getMessage(), previous: $exception);
}

try {
$this->curl->setopt_array($curl, $options);

/**
* @var string $result `curl_exec` returns string because `CURLOPT_RETURNTRANSFER` is set to `true`.
*/
$result = $this->curl->exec($curl);
} catch (CurlException $exception) {
throw new DownloadFileException($exception->getMessage(), previous: $exception);
} finally {
$this->curl->close($curl);
}

return $result;
}

public function downloadFileTo(string $url, string $savePath): void
{
set_error_handler(
static function (int $errorNumber, string $errorString): bool {
throw new SaveFileException($errorString);
},
);
try {
$fileHandler = fopen($savePath, 'wb');
} finally {
restore_error_handler();
}

$options = [
CURLOPT_URL => $url,
CURLOPT_FILE => $fileHandler,
CURLOPT_FILE => $stream,
CURLOPT_FAILONERROR => true,
CURLOPT_SHARE => $this->curlShareHandle,
];
Expand Down
27 changes: 8 additions & 19 deletions src/Transport/NativeTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function postWithFiles(string $url, array $data, array $files): ApiRespon
);
}

public function downloadFile(string $url): string
public function downloadFile(string $url, mixed $stream): void
{
set_error_handler(
static function (int $errorNumber, string $errorString): bool {
Expand All @@ -86,25 +86,14 @@ static function (int $errorNumber, string $errorString): bool {
);
try {
/**
* @var string We throw exception on error, so `file_get_contents()` returns string.
* @var resource $source We throw exception on error, so `fopen()` returns resource.
*/
return file_get_contents($url);
} finally {
restore_error_handler();
}
}

public function downloadFileTo(string $url, string $savePath): void
{
$content = $this->downloadFile($url);

set_error_handler(
static function (int $errorNumber, string $errorString): bool {
throw new SaveFileException($errorString);
},
);
try {
file_put_contents($savePath, $content);
$source = fopen($url, 'rb');
try {
stream_copy_to_stream($source, $stream);
} finally {
fclose($source);
}
} finally {
restore_error_handler();
}
Expand Down
57 changes: 26 additions & 31 deletions src/Transport/PsrTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,25 +75,41 @@ public function postWithFiles(string $url, array $data, array $files): ApiRespon
return $this->send($request);
}

public function downloadFile(string $url): string
public function downloadFile(string $url, mixed $stream): void
{
return $this->internalDownload($url)->getContents();
}
$request = $this->requestFactory->createRequest('GET', $url);

public function downloadFileTo(string $url, string $savePath): void
{
$body = $this->internalDownload($url);
try {
$response = $this->client->sendRequest($request);
} catch (ClientExceptionInterface $exception) {
throw new DownloadFileException($exception->getMessage(), previous: $exception);
}

$content = $body->detach();
$content ??= $body->getContents();
$body = $response->getBody();
if ($body->isSeekable()) {
$body->rewind();
}

$resource = $body->detach();

set_error_handler(
static function (int $errorNumber, string $errorString): bool {
throw new SaveFileException($errorString);
throw new DownloadFileException($errorString);
},
);
try {
file_put_contents($savePath, $content);
if ($resource === null) {
$result = fwrite($stream, (string) $body);
if ($result === false) {
throw new DownloadFileException('Failed to write file content to stream.');
}
return;
}
try {
stream_copy_to_stream($resource, $stream);
} finally {
fclose($resource);
}
} finally {
restore_error_handler();
}
Expand All @@ -113,25 +129,4 @@ private function send(RequestInterface $request): ApiResponse
$body->getContents(),
);
}

/**
* @throws DownloadFileException
*/
private function internalDownload(string $url): StreamInterface
{
$request = $this->requestFactory->createRequest('GET', $url);

try {
$response = $this->client->sendRequest($request);
} catch (ClientExceptionInterface $exception) {
throw new DownloadFileException($exception->getMessage(), previous: $exception);
}

$body = $response->getBody();
if ($body->isSeekable()) {
$body->rewind();
}

return $body;
}
}
18 changes: 3 additions & 15 deletions src/Transport/TransportInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,12 @@ public function post(string $url, string $body, array $headers): ApiResponse;
public function postWithFiles(string $url, array $data, array $files): ApiResponse;

/**
* Downloads a file by URL.
* Downloads a file by URL and writes its content to the given stream.
*
* @param string $url The URL of the file to download.
*
* @return string The file content.
*
* @throws DownloadFileException If an error occurred while downloading the file.
*/
public function downloadFile(string $url): string;

/**
* Downloads a file by URL and saves it to a file.
*
* @param string $url The URL of the file to download.
* @param string $savePath The path to save the file.
* @param resource $stream The stream to write the file content to.
*
* @throws DownloadFileException If an error occurred while downloading the file.
* @throws SaveFileException If an error occurred while saving the file.
*/
public function downloadFileTo(string $url, string $savePath): void;
public function downloadFile(string $url, mixed $stream): void;
}
35 changes: 35 additions & 0 deletions tests/DownloadedFile/DownloadedFileTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace Phptg\BotApi\Tests\DownloadedFile;

use PHPUnit\Framework\TestCase;
use Phptg\BotApi\DownloadedFile;

use function PHPUnit\Framework\assertSame;

final class DownloadedFileTest extends TestCase
{
public function testGetStream(): void
{
$stream = fopen('php://temp', 'r+b');
fwrite($stream, 'hello');
rewind($stream);

$file = new DownloadedFile($stream);

assertSame($stream, $file->getStream());
}

public function testGetBody(): void
{
$stream = fopen('php://temp', 'r+b');
fwrite($stream, 'hello-content');
rewind($stream);

$file = new DownloadedFile($stream);

assertSame('hello-content', $file->getBody());
}
}
1 change: 1 addition & 0 deletions tests/DownloadedFile/SaveTo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/test.txt
Loading