Update support Guzzle 8 and PSR-7 3

This commit is contained in:
Alex
2026-11-10 21:49:08 +03:00
parent 0ee7382264
commit 1aa13336de
8 changed files with 156 additions and 19 deletions
+16 -10
View File
@@ -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,15 +36,14 @@ jobs:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php-versions: [ "8.3", "8.4", "8.5" ]
guzzle-versions: [ "^7.0", "^8.0" ]
include:
- guzzle-versions: "^7.0"
laravel-version: "^12.0"
- guzzle-versions: "^8.0"
laravel-version: "^13.0"
name: PHP ${{ matrix.php-versions }} / Guzzle ${{ matrix.guzzle-versions }}
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
@@ -50,7 +56,7 @@ jobs:
coverage: xdebug
- name: Install composer dependencies
run: composer update --prefer-dist --no-interaction --with "guzzlehttp/guzzle:${{ matrix.guzzle-versions }}" --with "laravel/framework:${{ matrix.laravel-version }}"
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
+2 -1
View File
@@ -40,7 +40,8 @@
"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
View File
@@ -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';
+2
View File
@@ -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;
}
+10 -7
View File
@@ -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_filter(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(),
str_replace('HTTP/', '', $request->getProtocolVersion() ?? '1.1'),
)
);
+15
View File
@@ -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
{
+11
View File
@@ -38,6 +38,17 @@ final class GuzzleCompatibilityTest extends TestCase
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
{
+99
View File
@@ -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;
@@ -124,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
{
@@ -294,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(