From 0969b1e52336d1bff166faa7165909f451c839c6 Mon Sep 17 00:00:00 2001 From: Anton Date: Wed, 28 Feb 2024 21:44:26 +0800 Subject: [PATCH] Update codestyle standarts --- .php-cs-fixer.dist.php | 41 +++++++++++-------- src/Attribute/OnCommand.php | 4 +- src/Attribute/OnEvent.php | 4 +- .../Command/ButtonSetCommandsCommand.php | 2 +- .../Command/PolllingStartCommand.php | 4 +- src/TelegramBot/Command/SetWebhookCommand.php | 8 ++-- .../Command/WebhookInfoCommand.php | 8 ++-- src/TelegramBot/CommandMetadataProvider.php | 2 +- .../Controller/WebHookController.php | 2 +- src/TelegramBot/LongPollingService.php | 2 +- src/TelegramBot/UpdateHandler.php | 2 +- src/config/compilerpass.php | 4 +- src/config/services.php | 2 +- tests/CommandMetadataProviderTest.php | 19 +-------- tests/TestKernel.php | 2 +- tests/UpdateHandlerTest.php | 20 ++++----- 16 files changed, 59 insertions(+), 67 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index dabd02c..6a3ba70 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -1,18 +1,11 @@ in(__DIR__ . '/src') -; - $rules = [ // Rules that follow PSR-12 standard. - '@PSR12' => true, + '@PER-CS2.0' => true, // Rules that follow PSR-12 standard. This set contains rules that are risky. - '@PSR12:risky' => true, - - // Ignore function arguments lists that contain newlines (it for more readable attributes set right in constructors). - 'method_argument_space' => ['on_multiline' => 'ignore'], + '@PER-CS2.0:risky' => true, // PHP arrays should be declared using the short syntax. 'array_syntax' => ['syntax' => 'short'], @@ -23,9 +16,6 @@ // A single space or none should be between cast and variable. 'cast_spaces' => true, - // Class, trait and interface elements must be separated with one or none blank line. - 'class_attributes_separation' => ['elements' => ['method' => 'one']], - // There should not be any empty comments. 'no_empty_comment' => true, @@ -62,9 +52,6 @@ // Replace get_class calls on object variables with class keyword syntax. 'get_class_to_class_keyword' => true, - // Class DateTimeImmutable should be used instead of DateTime. - 'date_time_immutable' => true, - // Removes @param, @return and @var tags that don’t provide any useful information. 'no_superfluous_phpdoc_tags' => true, @@ -73,11 +60,31 @@ 'after_heredoc' => true, 'elements' => ['arrays', 'match', 'arguments', 'parameters'], ], + + // Empty body of class, interface, trait, enum or function must be abbreviated as {} and placed on the same line + 'single_line_empty_body' => false, + + // Functions should be used with $strict param set to true. + 'strict_param' => true, + + // Method chaining MUST be properly indented. + 'method_chaining_indentation' => true, + + // Add leading \ before function invocation to speed up resolving. + 'native_function_invocation' => [ + 'include' => ['@all'], + 'scope' => 'all', + 'strict' => true, + ], ]; return (new PhpCsFixer\Config()) ->setCacheFile(__DIR__ . '/var/.php-cs-fixer.cache') - ->setFinder($finder) + ->setFinder(PhpCsFixer\Finder::create() + ->in(__DIR__ . '/src') + ->in(__DIR__ . '/tests') + ->notContains(['@php-cs-fixer-ignore']) + ) ->setRules($rules) ->setRiskyAllowed(true) -; + ; diff --git a/src/Attribute/OnCommand.php b/src/Attribute/OnCommand.php index 42f5b59..920c101 100644 --- a/src/Attribute/OnCommand.php +++ b/src/Attribute/OnCommand.php @@ -18,7 +18,7 @@ public function __construct(string $command, string $description = '', bool $publish = false, int $priority = 0) { $this->event = Command::class; - $this->command = '/' . ltrim($command, '/'); + $this->command = '/' . \ltrim($command, '/'); $this->description = $description; $this->publish = $publish; $this->priority = $priority; @@ -28,7 +28,7 @@ public function __construct(string $command, string $description = '', bool $pub } if ($this->publish === true && $this->description === '') { - throw new \InvalidArgumentException(sprintf('Description should be set for publish command "%s"', $this->command)); + throw new \InvalidArgumentException(\sprintf('Description should be set for publish command "%s"', $this->command)); } } } diff --git a/src/Attribute/OnEvent.php b/src/Attribute/OnEvent.php index 0b53fe0..6d3d54c 100644 --- a/src/Attribute/OnEvent.php +++ b/src/Attribute/OnEvent.php @@ -17,8 +17,8 @@ public function __construct(string $event, int $priority = 0) $this->event = $event; $this->priority = $priority; - if (!is_subclass_of($event, Event::class)) { - throw new \InvalidArgumentException(sprintf('Event should implement %s', Event::class)); + if (!\is_subclass_of($event, Event::class)) { + throw new \InvalidArgumentException(\sprintf('Event should implement %s', Event::class)); } } } diff --git a/src/TelegramBot/Command/ButtonSetCommandsCommand.php b/src/TelegramBot/Command/ButtonSetCommandsCommand.php index 01a55e7..577aafa 100644 --- a/src/TelegramBot/Command/ButtonSetCommandsCommand.php +++ b/src/TelegramBot/Command/ButtonSetCommandsCommand.php @@ -47,7 +47,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $description = $this->descriptionProcessor->process($attr->description); - $output->writeln(sprintf("%s\t\t%s", $attr->command, $description)); + $output->writeln(\sprintf("%s\t\t%s", $attr->command, $description)); $commands[] = new Type\BotCommand(command: $attr->command, description: $description); } diff --git a/src/TelegramBot/Command/PolllingStartCommand.php b/src/TelegramBot/Command/PolllingStartCommand.php index 880e3b6..eb6af98 100644 --- a/src/TelegramBot/Command/PolllingStartCommand.php +++ b/src/TelegramBot/Command/PolllingStartCommand.php @@ -65,7 +65,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int foreach ($this->longPollingService->cunsumeUpdates() as $update) { $date = new \DateTimeImmutable('now'); $formattedDate = $date->format('Y-m-d H:i:s'); - $output->writeln(sprintf( + $output->writeln(\sprintf( '%s: [%s] Update object received', $formattedDate, $update->updateId, @@ -78,7 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int try { $this->botApi->call($callbackResponse); } catch (TelegramApiException $e) { - $output->writeln(sprintf( + $output->writeln(\sprintf( '%s: [%s] TelegramApiException (%s) %s', $formattedDate, $update->updateId, diff --git a/src/TelegramBot/Command/SetWebhookCommand.php b/src/TelegramBot/Command/SetWebhookCommand.php index ef1a413..4a2fba9 100644 --- a/src/TelegramBot/Command/SetWebhookCommand.php +++ b/src/TelegramBot/Command/SetWebhookCommand.php @@ -78,7 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::FAILURE; } - $io->success(sprintf('Webhook url set to "%s"', $url)); + $io->success(\sprintf('Webhook url set to "%s"', $url)); return Command::SUCCESS; } @@ -89,15 +89,15 @@ private function urlValidate(string $url): string throw new \RuntimeException('Url should not be blank'); } - if ((parse_url($url, PHP_URL_SCHEME) ?? 'https') !== 'https') { + if ((\parse_url($url, PHP_URL_SCHEME) ?? 'https') !== 'https') { throw new \RuntimeException('Url should starts with https://'); } - if (!str_starts_with($url, 'https://')) { + if (!\str_starts_with($url, 'https://')) { $url = 'https://' . $url; } - if (!filter_var($url, FILTER_VALIDATE_URL)) { + if (!\filter_var($url, FILTER_VALIDATE_URL)) { throw new \RuntimeException('Invalid url'); } diff --git a/src/TelegramBot/Command/WebhookInfoCommand.php b/src/TelegramBot/Command/WebhookInfoCommand.php index 36e8444..1fd8827 100644 --- a/src/TelegramBot/Command/WebhookInfoCommand.php +++ b/src/TelegramBot/Command/WebhookInfoCommand.php @@ -50,12 +50,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int $allowedUpdates = $webhookInfo->allowedUpdates === null ? 'All update types' - : '[' . implode(',', $webhookInfo->allowedUpdates) . ']' + : '[' . \implode(',', $webhookInfo->allowedUpdates) . ']' ; - $io->writeln(sprintf("Webhook url:\t\t%s", $webhookInfo->url)); - $io->writeln(sprintf("Max connections:\t%s", $webhookInfo->maxConnections)); - $io->writeln(sprintf("Allowed updates:\t%s", $allowedUpdates)); + $io->writeln(\sprintf("Webhook url:\t\t%s", $webhookInfo->url)); + $io->writeln(\sprintf("Max connections:\t%s", $webhookInfo->maxConnections)); + $io->writeln(\sprintf("Allowed updates:\t%s", $allowedUpdates)); return Command::SUCCESS; } diff --git a/src/TelegramBot/CommandMetadataProvider.php b/src/TelegramBot/CommandMetadataProvider.php index f681d61..29e34c2 100644 --- a/src/TelegramBot/CommandMetadataProvider.php +++ b/src/TelegramBot/CommandMetadataProvider.php @@ -32,7 +32,7 @@ public function gelMetadataList(): \Generator */ private function instantiateAttribute(string $controller): OnCommand|null { - [$class, $method] = explode('::', $controller, 2); + [$class, $method] = \explode('::', $controller, 2); $reflClass = new \ReflectionClass($class); $reflMethod = $reflClass->getMethod($method); $reflAttribute = $reflMethod->getAttributes(OnCommand::class)[0] ?? null; diff --git a/src/TelegramBot/Controller/WebHookController.php b/src/TelegramBot/Controller/WebHookController.php index 486f6ec..b3fa76c 100644 --- a/src/TelegramBot/Controller/WebHookController.php +++ b/src/TelegramBot/Controller/WebHookController.php @@ -39,7 +39,7 @@ public function __invoke(Request $request): Response } $response = new JsonResponse($this->updateHandler->handle($update)); - $response->headers->set('Content-Length', (string) strlen((string) $response->getContent())); + $response->headers->set('Content-Length', (string) \strlen((string) $response->getContent())); return $response; } diff --git a/src/TelegramBot/LongPollingService.php b/src/TelegramBot/LongPollingService.php index ae5827d..71b2c2f 100644 --- a/src/TelegramBot/LongPollingService.php +++ b/src/TelegramBot/LongPollingService.php @@ -39,7 +39,7 @@ public function setTimeLimit(int $timeLimit): void public function cunsumeUpdates(): \Generator { $start = \hrtime()[0]; - $checkTimeLimit = fn () => $this->timeLimit > 0 && \hrtime()[0] - $start >= $this->timeLimit; + $checkTimeLimit = fn() => $this->timeLimit > 0 && \hrtime()[0] - $start >= $this->timeLimit; while (true) { foreach ($this->getUpdates() as $update) { diff --git a/src/TelegramBot/UpdateHandler.php b/src/TelegramBot/UpdateHandler.php index 555d871..f387be4 100644 --- a/src/TelegramBot/UpdateHandler.php +++ b/src/TelegramBot/UpdateHandler.php @@ -52,7 +52,7 @@ private function createEvent(string $event, string $value, string $controller): private function runController(string $controller, object $update, array $params = []): mixed { /** @psalm-suppress PossiblyUndefinedArrayOffset */ - [$service, $method] = explode('::', $controller, 2); + [$service, $method] = \explode('::', $controller, 2); $controllerService = $this->serviceLocator->get($service); if ($update instanceof Update) { diff --git a/src/config/compilerpass.php b/src/config/compilerpass.php index a37e95e..f90f247 100644 --- a/src/config/compilerpass.php +++ b/src/config/compilerpass.php @@ -27,10 +27,10 @@ public function process(ContainerBuilder $container): void } // Commands have the highest priority by default - \usort($controllersMap, fn (array $a, array $b) => \str_starts_with($a['value'], '/') ? -1 : 1); + \usort($controllersMap, fn(array $a, array $b) => \str_starts_with($a['value'], '/') ? -1 : 1); // Sort by priority - \usort($controllersMap, fn (array $a, array $b) => $b['priority'] <=> $a['priority']); + \usort($controllersMap, fn(array $a, array $b) => $b['priority'] <=> $a['priority']); foreach ($controllersMap as $id => $row) { unset($controllersMap[$id]['priority']); diff --git a/src/config/services.php b/src/config/services.php index 4f1bae6..0ea8c0c 100644 --- a/src/config/services.php +++ b/src/config/services.php @@ -109,7 +109,7 @@ ->register('telegram_bot.description_processor', DummyDescriptionProcessor::class) ; - $controllerConfigurate = static function(ChildDefinition $definition, object $attribute, \ReflectionMethod $reflector): void { + $controllerConfigurate = static function (ChildDefinition $definition, object $attribute, \ReflectionMethod $reflector): void { $definition->addTag('telegram_bot.command', [ 'event' => $attribute->event, 'value' => $attribute->command ?? $attribute->callbackData ?? '', diff --git a/tests/CommandMetadataProviderTest.php b/tests/CommandMetadataProviderTest.php index 4277ebe..9f3008e 100644 --- a/tests/CommandMetadataProviderTest.php +++ b/tests/CommandMetadataProviderTest.php @@ -4,24 +4,9 @@ namespace Luzrain\TelegramBotBundle\Test; -use Luzrain\TelegramBotApi\BotApi; -use Luzrain\TelegramBotApi\ClientApi; use Luzrain\TelegramBotBundle\Attribute\OnCommand; -use Luzrain\TelegramBotBundle\TelegramBot\Command\ButtonDeleteCommand; -use Luzrain\TelegramBotBundle\TelegramBot\Command\ButtonSetCommandsCommand; -use Luzrain\TelegramBotBundle\TelegramBot\Command\DeleteWebhookCommand; -use Luzrain\TelegramBotBundle\TelegramBot\Command\PolllingStartCommand; -use Luzrain\TelegramBotBundle\TelegramBot\Command\SetWebhookCommand; -use Luzrain\TelegramBotBundle\TelegramBot\Command\WebhookInfoCommand; use Luzrain\TelegramBotBundle\TelegramBot\CommandMetadataProvider; -use Luzrain\TelegramBotBundle\TelegramBot\Controller\WebHookController; -use Luzrain\TelegramBotBundle\TelegramBot\LongPollingService; -use Luzrain\TelegramBotBundle\TelegramBot\UpdateHandler; -use Psr\Http\Client\ClientInterface; -use Psr\Http\Message\RequestFactoryInterface; -use Psr\Http\Message\StreamFactoryInterface; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; -use Symfony\Component\DependencyInjection\ContainerInterface; final class CommandMetadataProviderTest extends KernelTestCase { @@ -29,7 +14,7 @@ public function testCommandsMetadata(): void { /** @var CommandMetadataProvider $commandMetadataProvider */ $commandMetadataProvider = self::getContainer()->get('telegram_bot.command_metadata_provider'); - $list = iterator_to_array($commandMetadataProvider->gelMetadataList()); + $list = \iterator_to_array($commandMetadataProvider->gelMetadataList()); $this->assertCount(4, $list); $this->assertObjectInArray(new OnCommand('/start', '', false, 0), $list); @@ -40,6 +25,6 @@ public function testCommandsMetadata(): void private function assertObjectInArray(object $obj, array $array): void { - $this->assertContains(json_encode($obj), array_map(fn ($a) => json_encode($a), $array)); + $this->assertContains(\json_encode($obj), \array_map(fn($a) => \json_encode($a), $array)); } } diff --git a/tests/TestKernel.php b/tests/TestKernel.php index 6579f85..a8f1737 100644 --- a/tests/TestKernel.php +++ b/tests/TestKernel.php @@ -30,7 +30,7 @@ public function registerBundles(): iterable public function registerContainerConfiguration(LoaderInterface $loader) { - $loader->load(function(ContainerBuilder $container) { + $loader->load(function (ContainerBuilder $container) { $container->register('httpClient', ClientInterface::class); $container->register('requestFactory', RequestFactoryInterface::class); $container->register('streamFactory', StreamFactoryInterface::class); diff --git a/tests/UpdateHandlerTest.php b/tests/UpdateHandlerTest.php index 5c7f609..5c084df 100644 --- a/tests/UpdateHandlerTest.php +++ b/tests/UpdateHandlerTest.php @@ -22,11 +22,11 @@ public function setUp(): void public function testMessageHandle(): void { $controllerTestHelper = new ControllerTestHelper(); - $update = Update::fromJson(file_get_contents(__DIR__ . '/data/events/message.json')); + $update = Update::fromJson(\file_get_contents(__DIR__ . '/data/events/message.json')); $callbackResponse = $this->updateHandler->handle($update); $this->assertInstanceOf(Method\SendMessage::class, $callbackResponse); - $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"You wrote: test test"}', json_encode($callbackResponse)); + $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"You wrote: test test"}', \json_encode($callbackResponse)); $this->assertFalse($controllerTestHelper::$isStartCommand, '$isStartCommand'); $this->assertFalse($controllerTestHelper::$isTest1CommandCommand, '$isTest1CommandCommand'); $this->assertFalse($controllerTestHelper::$isTest2CommandCommand, '$isTest2CommandCommand'); @@ -39,11 +39,11 @@ public function testMessageHandle(): void public function testStartCommandHandle(): void { $controllerTestHelper = new ControllerTestHelper(); - $update = Update::fromJson(file_get_contents(__DIR__ . '/data/events/command1.json')); + $update = Update::fromJson(\file_get_contents(__DIR__ . '/data/events/command1.json')); $callbackResponse = $this->updateHandler->handle($update); $this->assertInstanceOf(Method\SendMessage::class, $callbackResponse); - $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"Start answer"}', json_encode($callbackResponse)); + $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"Start answer"}', \json_encode($callbackResponse)); $this->assertTrue($controllerTestHelper::$isStartCommand, '$isStartCommand'); $this->assertFalse($controllerTestHelper::$isTest1CommandCommand, '$isTest1CommandCommand'); $this->assertFalse($controllerTestHelper::$isTest2CommandCommand, '$isTest2CommandCommand'); @@ -56,11 +56,11 @@ public function testStartCommandHandle(): void public function testTest2CommandHandle(): void { $controllerTestHelper = new ControllerTestHelper(); - $update = Update::fromJson(file_get_contents(__DIR__ . '/data/events/command2.json')); + $update = Update::fromJson(\file_get_contents(__DIR__ . '/data/events/command2.json')); $callbackResponse = $this->updateHandler->handle($update); $this->assertInstanceOf(Method\SendMessage::class, $callbackResponse); - $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"Test2 answer"}', json_encode($callbackResponse)); + $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"Test2 answer"}', \json_encode($callbackResponse)); $this->assertFalse($controllerTestHelper::$isStartCommand, '$isStartCommand'); $this->assertFalse($controllerTestHelper::$isTest1CommandCommand, '$isTest1CommandCommand'); $this->assertTrue($controllerTestHelper::$isTest2CommandCommand, '$isTest2CommandCommand'); @@ -73,11 +73,11 @@ public function testTest2CommandHandle(): void public function testCallbackHandle(): void { $controllerTestHelper = new ControllerTestHelper(); - $update = Update::fromJson(file_get_contents(__DIR__ . '/data/events/callbackQuery.json')); + $update = Update::fromJson(\file_get_contents(__DIR__ . '/data/events/callbackQuery.json')); $callbackResponse = $this->updateHandler->handle($update); $this->assertInstanceOf(Method\SendMessage::class, $callbackResponse); - $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"Callback1 answer"}', json_encode($callbackResponse)); + $this->assertSame('{"method":"sendMessage","chat_id":123456789,"text":"Callback1 answer"}', \json_encode($callbackResponse)); $this->assertFalse($controllerTestHelper::$isStartCommand, '$isStartCommand'); $this->assertFalse($controllerTestHelper::$isTest1CommandCommand, '$isTest1CommandCommand'); $this->assertFalse($controllerTestHelper::$isTest2CommandCommand, '$isTest2CommandCommand'); @@ -90,7 +90,7 @@ public function testCallbackHandle(): void public function testUnregisteredCallbackHandle(): void { $controllerTestHelper = new ControllerTestHelper(); - $update = Update::fromJson(file_get_contents(__DIR__ . '/data/events/unknownCallbackQuery.json')); + $update = Update::fromJson(\file_get_contents(__DIR__ . '/data/events/unknownCallbackQuery.json')); $callbackResponse = $this->updateHandler->handle($update); $this->assertNull($callbackResponse); @@ -106,7 +106,7 @@ public function testUnregisteredCallbackHandle(): void public function testUnregisteredEventHandle(): void { $controllerTestHelper = new ControllerTestHelper(); - $update = Update::fromJson(file_get_contents(__DIR__ . '/data/events/myChatMember.json')); + $update = Update::fromJson(\file_get_contents(__DIR__ . '/data/events/myChatMember.json')); $callbackResponse = $this->updateHandler->handle($update); $this->assertNull($callbackResponse);