mirror of
https://github.com/BushlanovDev/max-bot-api-client-php.git
synced 2026-11-27 16:02:07 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1aa13336de | |||
| 0ee7382264 | |||
| f85391a164 | |||
| af1d93c125 |
@@ -6,8 +6,15 @@ jobs:
|
||||
|
||||
phpstan:
|
||||
|
||||
name: phpstan
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
stack:
|
||||
- { laravel: "^12.0", guzzle: "^7.0" }
|
||||
- { laravel: "^13.0", guzzle: "^7.0" }
|
||||
- { laravel: "^13.0", guzzle: "^8.0" }
|
||||
name: phpstan / Laravel ${{ matrix.stack.laravel }} / Guzzle ${{ matrix.stack.guzzle }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -20,7 +27,7 @@ jobs:
|
||||
coverage: none
|
||||
|
||||
- name: Install composer dependencies
|
||||
run: composer install --prefer-dist --no-interaction
|
||||
run: composer update --prefer-dist --no-interaction --with "guzzlehttp/guzzle:${{ matrix.stack.guzzle }}" --with "laravel/framework:${{ matrix.stack.laravel }}"
|
||||
|
||||
- name: Run Static Analysis
|
||||
run: ./vendor/bin/phpstan analyse -c phpstan.neon --error-format=github
|
||||
@@ -29,9 +36,14 @@ jobs:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
php-versions: [ "8.3", "8.4", "8.5" ]
|
||||
name: PHP ${{ matrix.php-versions }} Test on ubuntu-latest
|
||||
stack:
|
||||
- { laravel: "^12.0", guzzle: "^7.0" }
|
||||
- { laravel: "^13.0", guzzle: "^7.0" }
|
||||
- { laravel: "^13.0", guzzle: "^8.0" }
|
||||
name: PHP ${{ matrix.php-versions }} / Laravel ${{ matrix.stack.laravel }} / Guzzle ${{ matrix.stack.guzzle }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -44,7 +56,7 @@ jobs:
|
||||
coverage: xdebug
|
||||
|
||||
- name: Install composer dependencies
|
||||
run: composer install --prefer-dist --no-interaction
|
||||
run: composer update --prefer-dist --no-interaction --with "guzzlehttp/guzzle:${{ matrix.stack.guzzle }}" --with "laravel/framework:${{ matrix.stack.laravel }}"
|
||||
|
||||
- name: PHPUnit
|
||||
run: ./vendor/bin/phpunit --configuration=phpunit.xml --coverage-text
|
||||
|
||||
+6
-5
@@ -23,8 +23,8 @@
|
||||
"require": {
|
||||
"php": ">=8.3",
|
||||
"ext-json": "*",
|
||||
"guzzlehttp/guzzle": "^6.5.8||^7.0",
|
||||
"guzzlehttp/psr7": "^1.8||^2.0",
|
||||
"guzzlehttp/guzzle": "^6.5.8||^7.0||^8.0",
|
||||
"guzzlehttp/psr7": "^1.8||^2.0||^3.0",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0",
|
||||
"psr/http-message": "^1.0||^2.0",
|
||||
@@ -33,14 +33,15 @@
|
||||
"require-dev": {
|
||||
"friendsofphp/php-cs-fixer": "^3.77",
|
||||
"bushlanov-dev/php-coverage-badger": "^2.1",
|
||||
"laravel/framework": "^12.0",
|
||||
"laravel/framework": "^12.0||^13.0",
|
||||
"mikey179/vfsstream": "^1.6",
|
||||
"mockery/mockery": "^1.6",
|
||||
"orchestra/testbench": "^10.0",
|
||||
"orchestra/testbench": "^10.0||^11.0",
|
||||
"php-mock/php-mock-phpunit": "^2.13",
|
||||
"phpstan/phpstan": "^2.1",
|
||||
"phpunit/phpunit": "^12.0",
|
||||
"roave/security-advisories": "dev-latest"
|
||||
"roave/security-advisories": "dev-latest",
|
||||
"symfony/console": "^7.4||^8.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ class Api
|
||||
{
|
||||
public const string API_BASE_URL = 'https://platform-api2.max.ru';
|
||||
|
||||
public const string LIBRARY_VERSION = '1.8.0';
|
||||
public const string LIBRARY_VERSION = '1.8.1';
|
||||
|
||||
public const string API_VERSION = '1.2.5';
|
||||
|
||||
|
||||
@@ -61,6 +61,8 @@ final readonly class Client implements ClientApiInterface
|
||||
*/
|
||||
public function request(string $method, string $uri, array $queryParams = [], array $body = []): array
|
||||
{
|
||||
$method = strtoupper($method);
|
||||
|
||||
if (!empty($this->apiVersion)) {
|
||||
$queryParams['v'] = $this->apiVersion;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpFoundation\Request as RequestAlias;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -58,17 +59,19 @@ readonly class MaxBotManager
|
||||
/** @var WebhookHandler $webhookHandler */
|
||||
$webhookHandler = $this->container->make(WebhookHandler::class);
|
||||
|
||||
$headers = array_map(function ($values) {
|
||||
return array_filter($values, fn($value) => $value !== null);
|
||||
}, $request->headers->all());
|
||||
// WebhookHandler reads only the body and the secret header. Passing nothing else keeps
|
||||
// unrelated request data (other headers, protocol version) away from PSR-7 validation.
|
||||
$secret = array_values(array_map(
|
||||
static fn($value) => (string)$value,
|
||||
array_filter($request->headers->all('X-Max-Bot-Api-Secret'), 'is_scalar'),
|
||||
));
|
||||
|
||||
$webhookHandler->handle(
|
||||
new ServerRequest(
|
||||
$request->getMethod(),
|
||||
$request->getUri(),
|
||||
$headers,
|
||||
RequestAlias::METHOD_POST,
|
||||
'',
|
||||
$secret === [] ? [] : ['X-Max-Bot-Api-Secret' => $secret],
|
||||
$request->getContent(),
|
||||
$request->getProtocolVersion() ?? '1.1',
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
@@ -130,6 +130,21 @@ final class ClientTest extends TestCase
|
||||
$this->assertSame($responsePayload, $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function requestNormalizesHttpMethodToUpperCase(): void
|
||||
{
|
||||
$this->requestFactoryMock
|
||||
->expects($this->once())
|
||||
->method('createRequest')
|
||||
->with('GET', $this->anything())
|
||||
->willReturn($this->requestMock);
|
||||
|
||||
$this->responseMock->method('getStatusCode')->willReturn(200);
|
||||
$this->streamMock->method('__toString')->willReturn('{"id":987}');
|
||||
|
||||
$this->assertSame(['id' => 987], $this->client->request('get', '/me'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function successfulPostRequestWithJsonBody(): void
|
||||
{
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BushlanovDev\MaxMessengerBot\Tests;
|
||||
|
||||
use BushlanovDev\MaxMessengerBot\Client;
|
||||
use BushlanovDev\MaxMessengerBot\Exceptions\NetworkException;
|
||||
use BushlanovDev\MaxMessengerBot\Exceptions\RateLimitExceededException;
|
||||
use GuzzleHttp\Client as GuzzleClient;
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Middleware;
|
||||
use GuzzleHttp\Psr7\HttpFactory;
|
||||
use GuzzleHttp\Psr7\Request;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
#[CoversClass(Client::class)]
|
||||
final class GuzzleCompatibilityTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function sendsJsonThroughTheRealGuzzlePsr18Client(): void
|
||||
{
|
||||
$history = [];
|
||||
$client = $this->client([new Response(200, [], '{"message_id":"message-1"}')], $history);
|
||||
|
||||
self::assertSame(['message_id' => 'message-1'], $client->request('POST', '/messages', ['chat_id' => 123], ['text' => 'Hello']));
|
||||
self::assertCount(1, $history);
|
||||
$request = $history[0]['request'];
|
||||
self::assertSame('POST', $request->getMethod());
|
||||
self::assertSame('chat_id=123', $request->getUri()->getQuery());
|
||||
self::assertSame('test-token', $request->getHeaderLine('Authorization'));
|
||||
self::assertSame('application/json; charset=utf-8', $request->getHeaderLine('Content-Type'));
|
||||
self::assertSame('{"text":"Hello"}', (string) $request->getBody());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function sendsALowerCaseMethodInUpperCase(): void
|
||||
{
|
||||
$history = [];
|
||||
$client = $this->client([new Response(200, [], '{"user_id":1}')], $history);
|
||||
|
||||
self::assertSame(['user_id' => 1], $client->request('get', '/me'));
|
||||
self::assertCount(1, $history);
|
||||
self::assertSame('GET', $history[0]['request']->getMethod());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function preservesHttpErrorsForTheSdkToHandle(): void
|
||||
{
|
||||
$history = [];
|
||||
$client = $this->client([new Response(429, [], '{"message":"Too many requests"}')], $history);
|
||||
|
||||
$this->expectException(RateLimitExceededException::class);
|
||||
$client->request('POST', '/messages', [], ['text' => 'Hello']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function wrapsTransportFailuresWithoutRetryingAnOutboundMessage(): void
|
||||
{
|
||||
$history = [];
|
||||
$failure = new ConnectException('Connection timed out', new Request('POST', 'https://example.test/messages'));
|
||||
$client = $this->client([$failure, new Response(200, [], '{"success":true}')], $history);
|
||||
|
||||
try {
|
||||
$client->request('POST', '/messages', [], ['text' => 'Hello']);
|
||||
self::fail('The network failure must reach the caller.');
|
||||
} catch (NetworkException $exception) {
|
||||
self::assertSame($failure, $exception->getPrevious());
|
||||
self::assertCount(1, $history);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function uploadsAMultipartStreamUsingTheRealPsr7Factory(): void
|
||||
{
|
||||
$history = [];
|
||||
$client = $this->client([new Response(200, [], '{"token":"upload-1"}')], $history);
|
||||
$file = fopen('php://temp', 'w+');
|
||||
fwrite($file, 'file contents');
|
||||
rewind($file);
|
||||
|
||||
try {
|
||||
self::assertSame('{"token":"upload-1"}', $client->multipartUpload('https://example.test/upload', $file, 'ticket.pdf'));
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
|
||||
$request = $history[0]['request'];
|
||||
self::assertStringStartsWith('multipart/form-data; boundary=', $request->getHeaderLine('Content-Type'));
|
||||
self::assertStringContainsString('filename="ticket.pdf"', (string) $request->getBody());
|
||||
self::assertStringContainsString('file contents', (string) $request->getBody());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function uploadsEveryResumableChunkExactlyOnce(): void
|
||||
{
|
||||
$history = [];
|
||||
$client = $this->client([new Response(200), new Response(200, [], '{"token":"upload-1"}')], $history);
|
||||
$file = fopen('php://temp', 'w+');
|
||||
fwrite($file, 'abcdef');
|
||||
rewind($file);
|
||||
|
||||
try {
|
||||
self::assertSame('{"token":"upload-1"}', $client->resumableUpload('https://example.test/upload', $file, 'video.mp4', 6, 3));
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
|
||||
self::assertCount(2, $history);
|
||||
self::assertSame('bytes 0-2/6', $history[0]['request']->getHeaderLine('Content-Range'));
|
||||
self::assertSame('bytes 3-5/6', $history[1]['request']->getHeaderLine('Content-Range'));
|
||||
self::assertSame('abc', (string) $history[0]['request']->getBody());
|
||||
self::assertSame('def', (string) $history[1]['request']->getBody());
|
||||
}
|
||||
|
||||
private function client(array $queue, array &$history): Client
|
||||
{
|
||||
$stack = HandlerStack::create(new MockHandler($queue));
|
||||
$stack->push(Middleware::history($history));
|
||||
$factory = new HttpFactory();
|
||||
|
||||
return new Client('test-token', new GuzzleClient(['handler' => $stack]), $factory, $factory, 'https://example.test');
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ final class PollingStartCommandTest extends TestCase
|
||||
$this->command->setLaravel($this->container);
|
||||
|
||||
$application = new ConsoleApplication();
|
||||
$application->add($this->command);
|
||||
$application->addCommand($this->command);
|
||||
$commandInApp = $application->find('maxbot:polling:start');
|
||||
$this->tester = new CommandTester($commandInApp);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ final class WebhookListCommandTest extends TestCase
|
||||
$this->command->setLaravel($this->container);
|
||||
|
||||
$application = new ConsoleApplication();
|
||||
$application->add($this->command);
|
||||
$application->addCommand($this->command);
|
||||
$commandInApp = $application->find('maxbot:webhook:list');
|
||||
$this->tester = new CommandTester($commandInApp);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ final class WebhookSubscribeCommandTest extends TestCase
|
||||
$this->command->setLaravel($this->container);
|
||||
|
||||
$application = new ConsoleApplication();
|
||||
$application->add($this->command);
|
||||
$application->addCommand($this->command);
|
||||
$commandInApp = $application->find('maxbot:webhook:subscribe');
|
||||
$this->tester = new CommandTester($commandInApp);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ final class WebhookUnsubscribeCommandTest extends TestCase
|
||||
$this->command->setLaravel($this->container);
|
||||
|
||||
$application = new ConsoleApplication();
|
||||
$application->add($this->command);
|
||||
$application->addCommand($this->command);
|
||||
$commandInApp = $application->find('maxbot:webhook:unsubscribe');
|
||||
$this->tester = new CommandTester($commandInApp);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\Attributes\UsesClass;
|
||||
use PHPUnit\Framework\MockObject\MockObject;
|
||||
@@ -103,6 +104,7 @@ final class MaxBotManagerTest extends TestCase
|
||||
$this->container->instance(WebhookHandler::class, $webhookHandler);
|
||||
|
||||
$request = Request::create('/webhook', 'POST', content: '{"update_type":"message_created"}');
|
||||
$request->headers->set('X-Optional-Header', []);
|
||||
|
||||
$realUpdate = new MessageCreatedUpdate(
|
||||
time(),
|
||||
@@ -123,6 +125,76 @@ final class MaxBotManagerTest extends TestCase
|
||||
$this->assertTrue($wasDispatched, 'The update was not dispatched correctly.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{array<int, mixed>}>
|
||||
*/
|
||||
public static function headerValuesIgnoredByWebhookProvider(): array
|
||||
{
|
||||
return [
|
||||
'integer value' => [[42]],
|
||||
'only null' => [[null]],
|
||||
'nested array' => [[['nested']]],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $values
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('headerValuesIgnoredByWebhookProvider')]
|
||||
public function handleWebhookIgnoresHeadersTheHandlerDoesNotRead(array $values): void
|
||||
{
|
||||
$request = Request::create('/webhook', 'POST', content: '{"update_type":"message_created"}');
|
||||
$request->headers->set('X-Tenant', $values);
|
||||
|
||||
$this->assertSame([200, true], $this->handleWebhookWithUpdate($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{string}>
|
||||
*/
|
||||
public static function nonStandardServerProtocolProvider(): array
|
||||
{
|
||||
return [
|
||||
'empty' => [''],
|
||||
'lower case' => ['http/1.1'],
|
||||
'trailing space' => ['HTTP/1.1 '],
|
||||
'not a version' => ['INCLUDED'],
|
||||
];
|
||||
}
|
||||
|
||||
#[Test]
|
||||
#[DataProvider('nonStandardServerProtocolProvider')]
|
||||
public function handleWebhookIgnoresServerProtocol(string $protocol): void
|
||||
{
|
||||
$request = Request::create(
|
||||
'/webhook',
|
||||
'POST',
|
||||
server: ['SERVER_PROTOCOL' => $protocol],
|
||||
content: '{"update_type":"message_created"}',
|
||||
);
|
||||
|
||||
$this->assertSame([200, true], $this->handleWebhookWithUpdate($request));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function handleWebhookPassesSecretHeaderToHandler(): void
|
||||
{
|
||||
$request = Request::create('/webhook', 'POST', content: '{"update_type":"message_created"}');
|
||||
$request->headers->set('X-Max-Bot-Api-Secret', 'real-secret');
|
||||
|
||||
$this->assertSame([200, true], $this->handleWebhookWithUpdate($request, 'real-secret'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function handleWebhookReturns403WhenSecretHeaderIsNotScalar(): void
|
||||
{
|
||||
$request = Request::create('/webhook', 'POST', content: '{"update_type":"message_created"}');
|
||||
$request->headers->set('X-Max-Bot-Api-Secret', [['nested']]);
|
||||
|
||||
$this->assertSame([403, false], $this->handleWebhookWithUpdate($request, 'real-secret'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function handleWebhookReturns403OnSecurityException(): void
|
||||
{
|
||||
@@ -293,6 +365,34 @@ final class MaxBotManagerTest extends TestCase
|
||||
$dispatcher->dispatch($update);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the request through handleWebhook() with a real WebhookHandler.
|
||||
*
|
||||
* @return array{int, bool} The response status code and whether the update reached a handler.
|
||||
*/
|
||||
private function handleWebhookWithUpdate(Request $request, ?string $secret = null): array
|
||||
{
|
||||
$this->container->instance(WebhookHandler::class, new WebhookHandler(
|
||||
$this->updateDispatcher,
|
||||
$this->modelFactoryMock,
|
||||
$this->container->make(LoggerInterface::class),
|
||||
$secret,
|
||||
));
|
||||
|
||||
$this->modelFactoryMock->method('createUpdate')->willReturn(
|
||||
new MessageCreatedUpdate(time(), $this->createMinimalMessage(), 'ru-RU'),
|
||||
);
|
||||
|
||||
$wasDispatched = false;
|
||||
$this->updateDispatcher->addHandler(UpdateType::MessageCreated, function () use (&$wasDispatched) {
|
||||
$wasDispatched = true;
|
||||
});
|
||||
|
||||
$response = $this->manager->handleWebhook($request);
|
||||
|
||||
return [$response->getStatusCode(), $wasDispatched];
|
||||
}
|
||||
|
||||
private function createMinimalMessage(): Message
|
||||
{
|
||||
return new Message(
|
||||
|
||||
Reference in New Issue
Block a user