mirror of
https://github.com/BushlanovDev/max-bot-api-client-php.git
synced 2026-08-21 10:43:10 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 033fa42b79 | |||
| 94ec907506 | |||
| 869c254275 | |||
| cb8ad3f738 | |||
| 0f007bf94e | |||
| 3127f86c54 | |||
| ed715af3bc | |||
| 008d6f4e0e | |||
| 4784fcc97b |
@@ -5,7 +5,7 @@
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<mask id="a">
|
||||
<rect width="99" height="20" rx="3" fill="#fff"/>
|
||||
<rect width="99" height="20" fill="#fff"/>
|
||||
</mask>
|
||||
<g mask="url(#a)">
|
||||
<path fill="#555" d="M0 0h63v20H0z"/>
|
||||
|
Before Width: | Height: | Size: 902 B After Width: | Height: | Size: 895 B |
@@ -1,7 +1,7 @@
|
||||
# Max Bot API Client library for PHP
|
||||
# Max Messenger Bot API Client library for PHP
|
||||
|
||||
[](https://github.com/BushlanovDev/max-bot-api-client-php/actions)
|
||||
[](https://github.com/BushlanovDev/max-bot-api-client-php/actions)
|
||||
[](https://github.com/BushlanovDev/max-bot-api-client-php/actions)
|
||||
[](https://packagist.org/packages/bushlanov-dev/max-bot-api-client-php)
|
||||
[](https://github.com/BushlanovDev/max-bot-api-client-php)
|
||||
[](https://github.com/BushlanovDev/max-bot-api-client-php)
|
||||
@@ -51,11 +51,18 @@ use BushlanovDev\MaxMessengerBot\Api;
|
||||
|
||||
$api = new Api('YOUR_BOT_API_TOKEN');
|
||||
|
||||
// Загрузка файла
|
||||
$fileAttachmentRequest = $api->uploadAttachment(
|
||||
type: UploadType::File,
|
||||
filePath: __DIR__ . '/test.pdf',
|
||||
);
|
||||
|
||||
$api->sendMessage(
|
||||
userId: 123, // ID пользователя получателя сообщения
|
||||
chatId: 321, // Или ID чата, в который нужно отправить сообщение
|
||||
text: 'Привет!', // Текст сообщения, вы можете использовать HTML или Markdown
|
||||
attachments: [
|
||||
$fileAttachmentRequest,
|
||||
new InlineKeyboardAttachmentRequest([
|
||||
[new CallbackButton('Нажми меня!', 'payload_button1')],
|
||||
[new LinkButton('Нажми меня!', 'https://example.com')],
|
||||
|
||||
+75
-64
@@ -1,67 +1,78 @@
|
||||
{
|
||||
"name": "bushlanov-dev/max-bot-api-client-php",
|
||||
"description": "Max Bot API Client library",
|
||||
"keywords": ["max messenger", "bot", "max", "api", "max bot", "laravel", "laravel max bot"],
|
||||
"type": "library",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Aleksandr Bushlanov",
|
||||
"email": "alex@bushlanov.dev",
|
||||
"homepage": "https://bushlanov.dev",
|
||||
"role": "Developer"
|
||||
"name": "bushlanov-dev/max-bot-api-client-php",
|
||||
"description": "Max Bot API Client library",
|
||||
"keywords": [
|
||||
"max messenger",
|
||||
"bot",
|
||||
"max",
|
||||
"api",
|
||||
"max bot",
|
||||
"laravel",
|
||||
"laravel max bot"
|
||||
],
|
||||
"type": "library",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Aleksandr Bushlanov",
|
||||
"email": "alex@bushlanov.dev",
|
||||
"homepage": "https://bushlanov.dev",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=8.3",
|
||||
"ext-json": "*",
|
||||
"guzzlehttp/guzzle": "^6.5.8||^7.0",
|
||||
"guzzlehttp/psr7": "^1.8||^2.0",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0",
|
||||
"psr/http-message": "^1.0||^2.0",
|
||||
"psr/log": "^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"friendsofphp/php-cs-fixer": "^3.77",
|
||||
"bushlanov-dev/php-coverage-badger": "^2.1",
|
||||
"laravel/framework": "^11.0",
|
||||
"mikey179/vfsstream": "^1.6",
|
||||
"mockery/mockery": "^1.6",
|
||||
"orchestra/testbench": "^9.0",
|
||||
"php-mock/php-mock-phpunit": "^2.13",
|
||||
"phpstan/phpstan": "^2.1",
|
||||
"phpunit/phpunit": "^12.0",
|
||||
"roave/security-advisories": "dev-latest"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"BushlanovDev\\MaxMessengerBot\\": "src"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"BushlanovDev\\MaxMessengerBot\\Tests\\": "tests"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"BushlanovDev\\MaxMessengerBot\\Laravel\\MaxBotServiceProvider"
|
||||
],
|
||||
"aliases": {
|
||||
"MaxBot": "BushlanovDev\\MaxMessengerBot\\Laravel\\MaxBotFacade"
|
||||
}
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"analyse": "vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=256M",
|
||||
"format": "vendor/bin/php-cs-fixer fix --allow-risky=yes src",
|
||||
"test": "vendor/bin/phpunit",
|
||||
"test-coverage": "vendor/bin/phpunit --coverage-html coverage",
|
||||
"create-coverage-badge": [
|
||||
"vendor/bin/phpunit --coverage-clover clover.xml",
|
||||
"vendor/bin/php-coverage-badger --square clover.xml .github/badge-coverage.svg"
|
||||
]
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=8.3",
|
||||
"ext-json": "*",
|
||||
"guzzlehttp/guzzle": "^6.5.8||^7.0",
|
||||
"guzzlehttp/psr7": "^1.8||^2.0",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0",
|
||||
"psr/http-message": "^1.0||^2.0",
|
||||
"psr/log": "^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"friendsofphp/php-cs-fixer": "^3.77",
|
||||
"jaschilz/php-coverage-badger": "^2.0",
|
||||
"laravel/framework": "^11.0",
|
||||
"mikey179/vfsstream": "^1.6",
|
||||
"mockery/mockery": "^1.6",
|
||||
"orchestra/testbench": "^9.0",
|
||||
"php-mock/php-mock-phpunit": "^2.13",
|
||||
"phpstan/phpstan": "^2.1",
|
||||
"phpunit/phpunit": "^12.0",
|
||||
"roave/security-advisories": "dev-latest"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"BushlanovDev\\MaxMessengerBot\\": "src"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"BushlanovDev\\MaxMessengerBot\\Tests\\": "tests"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"BushlanovDev\\MaxMessengerBot\\Laravel\\MaxBotServiceProvider"
|
||||
],
|
||||
"aliases": {
|
||||
"MaxBot": "BushlanovDev\\MaxMessengerBot\\Laravel\\MaxBotFacade"
|
||||
}
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"analyse": "vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=256M",
|
||||
"format": "vendor/bin/php-cs-fixer fix --allow-risky=yes src",
|
||||
"test": "vendor/bin/phpunit",
|
||||
"test-coverage": "vendor/bin/phpunit --coverage-html coverage",
|
||||
"create-coverage-badge": ["vendor/bin/phpunit --coverage-clover clover.xml", "vendor/bin/php-coverage-badger clover.xml badge-coverage.svg"]
|
||||
}
|
||||
}
|
||||
|
||||
+36
-3
@@ -114,13 +114,16 @@ $api = new Api(
|
||||
|
||||
### Получение информации о боте
|
||||
|
||||
Возвращает информацию о текущем боте, который идентифицируется с помощью токена доступа.
|
||||
Метод возвращает ID бота, его имя и аватар (если есть).
|
||||
|
||||
```php
|
||||
$botInfo = $api->getBotInfo();
|
||||
```
|
||||
|
||||
### Редактирование информации о боте
|
||||
|
||||
Обратите внимание что данный метод отправляется PATCH запросом. Это значит, что будут обновлены только переданные
|
||||
Обратите внимание, что данный метод отправляется PATCH запросом. Это значит, что будут обновлены только переданные
|
||||
поля.
|
||||
В следующем примере мы изменяем только название бота и отчистим его описание. Остальные поля останутся неизменными.
|
||||
|
||||
@@ -137,6 +140,9 @@ $botInfo = $api->editBotInfo(
|
||||
|
||||
### Получение списка всех чатов бота
|
||||
|
||||
Возвращает информацию о чатах, в которых участвовал бот.
|
||||
Результат включает список чатов и маркер для перехода к следующей странице.
|
||||
|
||||
```php
|
||||
$chats = $api->getChats(
|
||||
count: 10, // Количество запрашиваемых чатов
|
||||
@@ -146,6 +152,8 @@ $chats = $api->getChats(
|
||||
|
||||
### Получение информации о чате по ссылке
|
||||
|
||||
Возвращает информацию о чате по его публичной ссылке, либо информацию о диалоге с пользователем по его username.
|
||||
|
||||
```php
|
||||
$chat = $api->getChatByLink('@super_chat'); // Публичная ссылка на чат или username пользователя
|
||||
```
|
||||
@@ -158,6 +166,8 @@ $chat = $api->getChat(12345);
|
||||
|
||||
### Редактирование информации о чате
|
||||
|
||||
Позволяет редактировать информацию о чате, включая название, иконку и закреплённое сообщение.
|
||||
|
||||
```php
|
||||
$chat = $api->editChat(
|
||||
chatId: 12345,
|
||||
@@ -175,6 +185,8 @@ $api->deleteChat(12345);
|
||||
|
||||
### Отправка действия в чат
|
||||
|
||||
Позволяет отправлять действия бота в чат, такие как «набор текста» или «отправка фото».
|
||||
|
||||
```php
|
||||
$api->sendAction(
|
||||
chatId: 12345,
|
||||
@@ -218,6 +230,8 @@ $api->leaveChat(12345);
|
||||
|
||||
### Получение администраторов чата
|
||||
|
||||
Возвращает всех администраторов чата. Бот должен быть администратором в запрашиваемом чате.
|
||||
|
||||
```php
|
||||
$adminsChatMemberList = $api->getAdmins(12345);
|
||||
```
|
||||
@@ -225,7 +239,7 @@ $adminsChatMemberList = $api->getAdmins(12345);
|
||||
### Назначение администраторов чата
|
||||
|
||||
```php
|
||||
$chatMemberList = $api->addAdmins(
|
||||
$api->addAdmins(
|
||||
chatId: 12345,
|
||||
admins: [
|
||||
new ChatAdmin(123, [ChatAdminPermission::ReadAllMessages]),
|
||||
@@ -278,6 +292,10 @@ $subscriptions = $api->getSubscriptions();
|
||||
|
||||
### Создание Webhook-подписки
|
||||
|
||||
Подписывает бота на получение обновлений через WebHook.
|
||||
После вызова этого метода бот будет получать уведомления о новых событиях в чатах на указанный URL.
|
||||
Ваш сервер должен прослушивать один из следующих портов: 80, 8080, 443, 8443, 16384-32383.
|
||||
|
||||
```php
|
||||
$api->subscribe(
|
||||
url: 'https://example.com/webhook', // URL на который будут приходить хуки. Должен начинаться с http(s)://
|
||||
@@ -294,6 +312,11 @@ $api->unsubscribe('https://example.com/webhook');
|
||||
|
||||
### Получение обновлений через Long-Polling
|
||||
|
||||
Этот метод можно использовать для получения обновлений, если ваш бот не подписан на WebHook. Метод использует долгий опрос (long polling).
|
||||
Каждое обновление имеет свой номер последовательности. Свойство marker в ответе указывает на следующее ожидаемое обновление.
|
||||
Все предыдущие обновления считаются завершенными после прохождения параметра marker.
|
||||
Если параметр marker не передан, бот получит все обновления, произошедшие после последнего подтверждения.
|
||||
|
||||
```php
|
||||
$updateList = $api->getUpdates(
|
||||
limit: 10, // Максимальное количество обновлений для получения [1-1000] (необязательно)
|
||||
@@ -309,7 +332,8 @@ $updateList = $api->getUpdates(
|
||||
|
||||
```php
|
||||
$uploadEndpoint = $api->getUploadUrl(UploadType::Video);
|
||||
// Далее вы можете загрузить файл по полученному URL самостоятельно или воспользоваться методом Client::upload()
|
||||
// Далее вы можете загрузить файл по полученному URL самостоятельно
|
||||
// или воспользоваться методами Client::multipartUpload(), Client::resumableUpload(), Api::uploadFile()
|
||||
```
|
||||
|
||||
### Загрузка файла
|
||||
@@ -327,6 +351,10 @@ $photoAttachmentRequest = $api->uploadAttachment(
|
||||
|
||||
### Получение списка сообщений из чата
|
||||
|
||||
Возвращает сообщения в чате: страницу с результатами и маркер, указывающий на следующую страницу.
|
||||
Сообщения возвращаются в обратном порядке, то есть последние сообщения в чате будут первыми в массиве.
|
||||
Поэтому, если вы используете параметры from и to, то to должно быть меньше, чем from.
|
||||
|
||||
```php
|
||||
$messages = $api->getMessages(
|
||||
chatId: 12345, // ID чата, чтобы получить сообщения из определённого чата (необязательно)
|
||||
@@ -366,6 +394,9 @@ $message = $api->sendMessage(
|
||||
|
||||
### Редактирование сообщения
|
||||
|
||||
Редактирует сообщение в чате. Если поле attachments равно null, вложения текущего сообщения не изменяются.
|
||||
Если в этом поле передан пустой список, все вложения будут удалены.
|
||||
|
||||
```php
|
||||
$api->editMessage(
|
||||
messageId: 12345,
|
||||
@@ -391,6 +422,8 @@ $message = $api->getMessageById(12345);
|
||||
|
||||
### Получение детальной информации о видео
|
||||
|
||||
Возвращает подробную информацию о приклеплённом видео. URL-адреса воспроизведения и дополнительные метаданные.
|
||||
|
||||
```php
|
||||
$videoAttachmentDetails = $api->getVideoAttachmentDetails('some-video-token');
|
||||
```
|
||||
|
||||
+35
-3
@@ -48,7 +48,7 @@ use RuntimeException;
|
||||
*/
|
||||
class Api
|
||||
{
|
||||
public const string LIBRARY_VERSION = '1.0.1';
|
||||
public const string LIBRARY_VERSION = '1.2.1';
|
||||
|
||||
public const string API_VERSION = '0.0.6';
|
||||
|
||||
@@ -75,6 +75,8 @@ class Api
|
||||
private const string ACTION_ANSWERS = '/answers';
|
||||
private const string ACTION_VIDEO_DETAILS = '/videos/%s';
|
||||
|
||||
private const int RESUMABLE_UPLOAD_THRESHOLD_BYTES = 10 * 1024 * 1024; // 10 MB
|
||||
|
||||
private readonly ClientApiInterface $client;
|
||||
|
||||
private readonly ModelFactory $modelFactory;
|
||||
@@ -443,6 +445,35 @@ class Api
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a file to the specified URL.
|
||||
*
|
||||
* @param string $uploadUrl The target URL for the upload.
|
||||
* @param resource $fileHandle A stream resource pointing to the file.
|
||||
* @param string $fileName The desired file name for the upload.
|
||||
*
|
||||
* @return string The body of the final response from the server.
|
||||
* @throws ClientApiException
|
||||
* @throws NetworkException
|
||||
* @throws SerializationException
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function uploadFile(string $uploadUrl, mixed $fileHandle, string $fileName): string
|
||||
{
|
||||
$stat = fstat($fileHandle);
|
||||
if (!is_array($stat)) {
|
||||
throw new RuntimeException('File handle is not a valid resource.');
|
||||
}
|
||||
|
||||
rewind($fileHandle);
|
||||
|
||||
if ($stat['size'] < self::RESUMABLE_UPLOAD_THRESHOLD_BYTES) {
|
||||
return $this->client->multipartUpload($uploadUrl, $fileHandle, $fileName);
|
||||
}
|
||||
|
||||
return $this->client->resumableUpload($uploadUrl, $fileHandle, $fileName, $stat['size']);
|
||||
}
|
||||
|
||||
/**
|
||||
* A simplified method for uploading a file and getting the resulting attachment object.
|
||||
*
|
||||
@@ -479,7 +510,8 @@ class Api
|
||||
"API did not return a pre-upload token for type '$type->value'."
|
||||
);
|
||||
}
|
||||
$this->client->upload($uploadEndpoint->url, $fileHandle, basename($filePath));
|
||||
|
||||
$this->uploadFile($uploadEndpoint->url, $fileHandle, basename($filePath));
|
||||
fclose($fileHandle);
|
||||
|
||||
return match ($type) {
|
||||
@@ -489,7 +521,7 @@ class Api
|
||||
}
|
||||
|
||||
// For images and files, the token is in the response *after* the upload.
|
||||
$responseBody = $this->client->upload($uploadEndpoint->url, $fileHandle, basename($filePath));
|
||||
$responseBody = $this->uploadFile($uploadEndpoint->url, $fileHandle, basename($filePath));
|
||||
fclose($fileHandle);
|
||||
|
||||
try {
|
||||
|
||||
+65
-1
@@ -21,6 +21,7 @@ use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamFactoryInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Psr\Log\NullLogger;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* The low-level HTTP client responsible for communicating with the Max Bot API.
|
||||
@@ -122,7 +123,7 @@ final readonly class Client implements ClientApiInterface
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function upload(string $uri, mixed $fileContents, string $fileName): string
|
||||
public function multipartUpload(string $uri, mixed $fileContents, string $fileName): string
|
||||
{
|
||||
$boundary = '--------------------------' . microtime(true);
|
||||
$bodyStream = $this->streamFactory->createStream();
|
||||
@@ -155,6 +156,69 @@ final readonly class Client implements ClientApiInterface
|
||||
return (string)$response->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function resumableUpload(
|
||||
string $uploadUrl,
|
||||
mixed $fileResource,
|
||||
string $fileName,
|
||||
int $fileSize,
|
||||
int $chunkSize = 1048576,
|
||||
): string {
|
||||
if (!is_resource($fileResource) || get_resource_type($fileResource) !== 'stream') {
|
||||
throw new InvalidArgumentException('fileResource must be a valid stream resource.');
|
||||
}
|
||||
|
||||
// @phpstan-ignore-next-line
|
||||
if ($fileSize <= 0) {
|
||||
throw new InvalidArgumentException('File size must be greater than 0.');
|
||||
}
|
||||
|
||||
$startByte = 0;
|
||||
$finalResponseBody = '';
|
||||
|
||||
while (!feof($fileResource)) {
|
||||
$chunk = fread($fileResource, $chunkSize);
|
||||
if ($chunk === false) {
|
||||
// @codeCoverageIgnoreStart
|
||||
throw new RuntimeException('Failed to read chunk from file stream.');
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
$chunkLength = strlen($chunk);
|
||||
if ($chunkLength === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
$endByte = $startByte + $chunkLength - 1;
|
||||
|
||||
$chunkStream = $this->streamFactory->createStream($chunk);
|
||||
$request = $this->requestFactory->createRequest('POST', $uploadUrl)
|
||||
->withBody($chunkStream)
|
||||
->withHeader('Content-Type', 'application/octet-stream')
|
||||
->withHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"')
|
||||
->withHeader('Content-Range', "bytes {$startByte}-{$endByte}/{$fileSize}");
|
||||
|
||||
try {
|
||||
$response = $this->httpClient->sendRequest($request);
|
||||
} catch (ClientExceptionInterface $e) {
|
||||
throw new NetworkException($e->getMessage(), $e->getCode(), $e);
|
||||
}
|
||||
|
||||
$this->handleErrorResponse($response);
|
||||
|
||||
// The final response might contain the retval
|
||||
$finalResponseBody = (string)$response->getBody();
|
||||
|
||||
$startByte += $chunkLength;
|
||||
}
|
||||
|
||||
// According to docs, for video/audio the token is sent separately,
|
||||
// and the upload response contains 'retval'. We return the body of the last response.
|
||||
return $finalResponseBody;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the response for an error status code and throws a corresponding typed exception.
|
||||
*
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace BushlanovDev\MaxMessengerBot;
|
||||
use BushlanovDev\MaxMessengerBot\Exceptions\ClientApiException;
|
||||
use BushlanovDev\MaxMessengerBot\Exceptions\NetworkException;
|
||||
use BushlanovDev\MaxMessengerBot\Exceptions\SerializationException;
|
||||
use RuntimeException;
|
||||
|
||||
interface ClientApiInterface
|
||||
{
|
||||
@@ -37,5 +38,28 @@ interface ClientApiInterface
|
||||
* @throws NetworkException
|
||||
* @throws SerializationException
|
||||
*/
|
||||
public function upload(string $uri, mixed $fileContents, string $fileName): string;
|
||||
public function multipartUpload(string $uri, mixed $fileContents, string $fileName): string;
|
||||
|
||||
/**
|
||||
* Uploads a file in chunks using the resumable upload method.
|
||||
* The caller is responsible for opening and closing the file resource.
|
||||
*
|
||||
* @param string $uploadUrl The target URL for the upload.
|
||||
* @param resource $fileResource A stream resource pointing to the file.
|
||||
* @param string $fileName The desired file name for the upload.
|
||||
* @param int<1, max> $fileSize The total size of the file in bytes.
|
||||
* @param int<1, max> $chunkSize The size of each chunk in bytes.
|
||||
*
|
||||
* @return string The body of the final response from the server.
|
||||
* @throws NetworkException
|
||||
* @throws ClientApiException
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function resumableUpload(
|
||||
string $uploadUrl,
|
||||
$fileResource,
|
||||
string $fileName,
|
||||
int $fileSize,
|
||||
int $chunkSize = 1048576,
|
||||
): string;
|
||||
}
|
||||
|
||||
+92
-9
@@ -461,7 +461,7 @@ final class ApiTest extends TestCase
|
||||
$this->clientMock->method('request')->willReturn(['url' => $uploadUrl]);
|
||||
$this->modelFactoryMock->method('createUploadEndpoint')->willReturn(new UploadEndpoint($uploadUrl));
|
||||
|
||||
$this->clientMock->method('upload')->willReturn($uploadResponseJson);
|
||||
$this->clientMock->method('multipartUpload')->willReturn($uploadResponseJson);
|
||||
|
||||
$result = $this->api->uploadAttachment(UploadType::Image, $filePath);
|
||||
|
||||
@@ -480,7 +480,7 @@ final class ApiTest extends TestCase
|
||||
$this->clientMock->method('request')->willReturn(['url' => $uploadUrl]);
|
||||
$this->modelFactoryMock->method('createUploadEndpoint')->willReturn(new UploadEndpoint($uploadUrl));
|
||||
|
||||
$this->clientMock->method('upload')->willReturn($uploadResponseJson);
|
||||
$this->clientMock->method('multipartUpload')->willReturn($uploadResponseJson);
|
||||
|
||||
$result = $this->api->uploadAttachment(UploadType::File, $filePath);
|
||||
|
||||
@@ -514,7 +514,7 @@ final class ApiTest extends TestCase
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('upload')
|
||||
->method('multipartUpload')
|
||||
->with($uploadUrl, $this->isResource(), basename($filePath))
|
||||
->willReturn($uploadResponse);
|
||||
|
||||
@@ -551,7 +551,7 @@ final class ApiTest extends TestCase
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('upload')
|
||||
->method('multipartUpload')
|
||||
->with($uploadUrl, $this->isResource(), basename($filePath))
|
||||
->willReturn($uploadResponse);
|
||||
|
||||
@@ -726,7 +726,7 @@ final class ApiTest extends TestCase
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('upload')
|
||||
->method('multipartUpload')
|
||||
->with($uploadUrl, $this->isResource(), basename($filePath))
|
||||
->willReturn(json_encode($invalidUploadResponse));
|
||||
|
||||
@@ -769,7 +769,7 @@ final class ApiTest extends TestCase
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('upload')
|
||||
->method('multipartUpload')
|
||||
->with($uploadUrl, $this->isResource(), basename($filePath))
|
||||
->willReturn(json_encode($uploadResponse));
|
||||
|
||||
@@ -1983,7 +1983,7 @@ final class ApiTest extends TestCase
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('upload')
|
||||
->method('multipartUpload')
|
||||
->willReturn($invalidJsonResponse);
|
||||
|
||||
try {
|
||||
@@ -2017,7 +2017,7 @@ final class ApiTest extends TestCase
|
||||
->with($getUploadUrlResponse)
|
||||
->willReturn($expectedEndpoint);
|
||||
|
||||
$this->clientMock->expects($this->never())->method('upload');
|
||||
$this->clientMock->expects($this->never())->method('multipartUpload');
|
||||
|
||||
try {
|
||||
$this->api->uploadAttachment(UploadType::Video, $filePath);
|
||||
@@ -2042,7 +2042,7 @@ final class ApiTest extends TestCase
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('upload')
|
||||
->method('multipartUpload')
|
||||
->willReturn($invalidUploadResponse);
|
||||
|
||||
try {
|
||||
@@ -2051,4 +2051,87 @@ final class ApiTest extends TestCase
|
||||
unlink($filePath);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
#[RunInSeparateProcess]
|
||||
#[PreserveGlobalState(false)]
|
||||
public function uploadFileUsesMultipartForSmallFiles(): void
|
||||
{
|
||||
$uploadUrl = 'https://upload.server/path';
|
||||
$fileName = 'small.txt';
|
||||
$fileContents = 'content';
|
||||
$fileHandle = fopen('php://memory', 'w+');
|
||||
fwrite($fileHandle, $fileContents);
|
||||
rewind($fileHandle);
|
||||
|
||||
$smallFileSize = strlen($fileContents);
|
||||
$expectedResponse = 'multipart-response';
|
||||
|
||||
$fstatMock = $this->getFunctionMock('BushlanovDev\MaxMessengerBot', 'fstat');
|
||||
$fstatMock->expects($this->once())->with($fileHandle)->willReturn(['size' => $smallFileSize]);
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('multipartUpload')
|
||||
->with($uploadUrl, $fileHandle, $fileName)
|
||||
->willReturn($expectedResponse);
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->never())
|
||||
->method('resumableUpload');
|
||||
|
||||
$result = $this->api->uploadFile($uploadUrl, $fileHandle, $fileName);
|
||||
|
||||
$this->assertSame($expectedResponse, $result);
|
||||
fclose($fileHandle);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
#[RunInSeparateProcess]
|
||||
#[PreserveGlobalState(false)]
|
||||
public function uploadFileUsesResumableForLargeFiles(): void
|
||||
{
|
||||
$uploadUrl = 'https://upload.server/path';
|
||||
$fileName = 'large.zip';
|
||||
$fileHandle = fopen('php://memory', 'w+');
|
||||
|
||||
rewind($fileHandle);
|
||||
|
||||
$largeFileSize = 10 * 1024 * 1024;
|
||||
$expectedResponse = 'resumable-response';
|
||||
|
||||
$fstatMock = $this->getFunctionMock('BushlanovDev\MaxMessengerBot', 'fstat');
|
||||
$fstatMock->expects($this->once())->with($fileHandle)->willReturn(['size' => $largeFileSize]);
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->once())
|
||||
->method('resumableUpload')
|
||||
->with($uploadUrl, $fileHandle, $fileName, $largeFileSize)
|
||||
->willReturn($expectedResponse);
|
||||
|
||||
$this->clientMock
|
||||
->expects($this->never())
|
||||
->method('multipartUpload');
|
||||
|
||||
$result = $this->api->uploadFile($uploadUrl, $fileHandle, $fileName);
|
||||
|
||||
$this->assertSame($expectedResponse, $result);
|
||||
fclose($fileHandle);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
#[RunInSeparateProcess]
|
||||
#[PreserveGlobalState(false)]
|
||||
public function uploadFileThrowsExceptionWhenFstatFails(): void
|
||||
{
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage('File handle is not a valid resource.');
|
||||
|
||||
$fileHandle = fopen('php://memory', 'r');
|
||||
|
||||
$fstatMock = $this->getFunctionMock('BushlanovDev\MaxMessengerBot', 'fstat');
|
||||
$fstatMock->expects($this->once())->with($fileHandle)->willReturn(false);
|
||||
|
||||
$this->api->uploadFile('http://a.b', $fileHandle, 'file.txt');
|
||||
}
|
||||
}
|
||||
|
||||
+132
-5
@@ -313,7 +313,7 @@ final class ClientTest extends TestCase
|
||||
$this->responseMock->method('getStatusCode')->willReturn(200);
|
||||
$this->streamMock->method('__toString')->willReturn(json_encode($responsePayload));
|
||||
|
||||
$result = $this->client->upload($uploadUrl, $fileContents, $fileName);
|
||||
$result = $this->client->multipartUpload($uploadUrl, $fileContents, $fileName);
|
||||
$this->assertSame(json_encode($responsePayload), $result);
|
||||
}
|
||||
|
||||
@@ -332,11 +332,11 @@ final class ClientTest extends TestCase
|
||||
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
|
||||
$this->requestMock->method('withHeader')->willReturn($this->requestMock);
|
||||
$this->requestMock->method('withBody')->willReturn($this->requestMock);
|
||||
$this->httpClientMock->method('sendRequest')->willReturn($this->responseMock);
|
||||
// $this->httpClientMock->method('sendRequest')->willReturn($this->responseMock);
|
||||
$this->responseMock->method('getStatusCode')->willReturn(200);
|
||||
$this->streamMock->method('__toString')->willReturn(json_encode($responsePayload));
|
||||
|
||||
$result = $this->client->upload($uploadUrl, $tmpFileHandle, $fileName);
|
||||
$result = $this->client->multipartUpload($uploadUrl, $tmpFileHandle, $fileName);
|
||||
|
||||
$this->assertSame(json_encode($responsePayload), $result);
|
||||
fclose($tmpFileHandle);
|
||||
@@ -358,7 +358,7 @@ final class ClientTest extends TestCase
|
||||
->with($this->requestMock)
|
||||
->willThrowException($psrException);
|
||||
|
||||
$this->client->upload('http://some.url', 'content', 'file.txt');
|
||||
$this->client->multipartUpload('http://some.url', 'content', 'file.txt');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
@@ -406,7 +406,134 @@ final class ClientTest extends TestCase
|
||||
$this->responseMock->method('getStatusCode')->willReturn(200);
|
||||
$this->streamMock->method('__toString')->willReturn($rawResponse);
|
||||
|
||||
$result = $this->client->upload($uploadUrl, $fileContents, $fileName);
|
||||
$result = $this->client->multipartUpload($uploadUrl, $fileContents, $fileName);
|
||||
$this->assertSame($rawResponse, $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function resumableUploadThrowsExceptionForInvalidResource(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('fileResource must be a valid stream resource.');
|
||||
|
||||
$this->client->resumableUpload('http://a.b', 'not-a-resource', 'file.txt', 100);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function resumableUploadThrowsExceptionForZeroFileSize(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('File size must be greater than 0.');
|
||||
|
||||
$fileResource = fopen('php://memory', 'r');
|
||||
$this->client->resumableUpload('http://a.b', $fileResource, 'file.txt', 0);
|
||||
fclose($fileResource);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function resumableUploadThrowsNetworkExceptionOnChunkUploadFailure(): void
|
||||
{
|
||||
$this->expectException(NetworkException::class);
|
||||
|
||||
$fileResource = fopen('php://memory', 'w+');
|
||||
fwrite($fileResource, 'some data');
|
||||
rewind($fileResource);
|
||||
|
||||
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
|
||||
$this->requestMock->method('withBody')->willReturnSelf();
|
||||
$this->requestMock->method('withHeader')->willReturnSelf();
|
||||
|
||||
$psrException = new class extends \Exception implements ClientExceptionInterface {};
|
||||
$this->httpClientMock
|
||||
->method('sendRequest')
|
||||
->willThrowException($psrException);
|
||||
|
||||
$this->client->resumableUpload('http://a.b', $fileResource, 'file.txt', 9);
|
||||
fclose($fileResource);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function resumableUploadSuccessfullyUploadsSingleChunk(): void
|
||||
{
|
||||
$fileContents = 'test-data';
|
||||
$fileResource = fopen('php://memory', 'w+');
|
||||
fwrite($fileResource, $fileContents);
|
||||
rewind($fileResource);
|
||||
|
||||
$uploadUrl = 'http://a.b';
|
||||
$fileName = 'file.txt';
|
||||
$fileSize = strlen($fileContents);
|
||||
|
||||
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
|
||||
$this->requestMock->method('withBody')->willReturnSelf();
|
||||
$this->requestMock->method('withHeader')->willReturnSelf();
|
||||
|
||||
$this->httpClientMock
|
||||
->expects($this->once())
|
||||
->method('sendRequest')
|
||||
->with($this->requestMock)
|
||||
->willReturn($this->responseMock);
|
||||
|
||||
$this->responseMock->method('getStatusCode')->willReturn(200);
|
||||
$this->streamMock->method('__toString')->willReturn('<retval>1</retval>');
|
||||
|
||||
$result = $this->client->resumableUpload($uploadUrl, $fileResource, $fileName, $fileSize);
|
||||
|
||||
$this->assertSame('<retval>1</retval>', $result);
|
||||
fclose($fileResource);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function resumableUploadSuccessfullyUploadsMultipleChunks(): void
|
||||
{
|
||||
$fileContents = str_repeat('A', 3 * 1024 * 1024); // 3 MB
|
||||
$fileResource = fopen('php://memory', 'w+');
|
||||
fwrite($fileResource, $fileContents);
|
||||
rewind($fileResource);
|
||||
|
||||
$uploadUrl = 'http://a.b';
|
||||
$fileName = 'bigfile.bin';
|
||||
$fileSize = strlen($fileContents);
|
||||
|
||||
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
|
||||
$this->requestMock->method('withBody')->willReturnSelf();
|
||||
$this->requestMock->method('withHeader')->willReturnSelf();
|
||||
|
||||
$this->httpClientMock
|
||||
->expects($this->exactly(3))
|
||||
->method('sendRequest')
|
||||
->willReturnOnConsecutiveCalls(
|
||||
$this->responseMock,
|
||||
$this->responseMock,
|
||||
$this->responseMock,
|
||||
);
|
||||
|
||||
$this->responseMock->method('getStatusCode')->willReturn(200);
|
||||
$this->streamMock
|
||||
->method('__toString')
|
||||
->willReturnOnConsecutiveCalls('', '', '<retval>1</retval>');
|
||||
|
||||
$result = $this->client->resumableUpload($uploadUrl, $fileResource, $fileName, $fileSize, 1024 * 1024);
|
||||
|
||||
$this->assertSame('<retval>1</retval>', $result);
|
||||
fclose($fileResource);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function resumableUploadStopsOnEmptyChunk(): void
|
||||
{
|
||||
$fileResource = fopen('php://memory', 'w+');
|
||||
rewind($fileResource);
|
||||
|
||||
$uploadUrl = 'http://a.b';
|
||||
$fileName = 'empty.txt';
|
||||
|
||||
$this->requestFactoryMock->expects($this->never())->method('createRequest');
|
||||
$this->httpClientMock->expects($this->never())->method('sendRequest');
|
||||
|
||||
$result = $this->client->resumableUpload($uploadUrl, $fileResource, $fileName, 100);
|
||||
|
||||
$this->assertSame('', $result);
|
||||
fclose($fileResource);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user