Skip to content

Commit

Permalink
Update codestyle standarts
Browse files Browse the repository at this point in the history
  • Loading branch information
luzrain committed Feb 28, 2024
1 parent 3d03db6 commit 0969b1e
Show file tree
Hide file tree
Showing 16 changed files with 59 additions and 67 deletions.
41 changes: 24 additions & 17 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
<?php

$finder = PhpCsFixer\Finder::create()
->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'],
Expand All @@ -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,

Expand Down Expand Up @@ -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,

Expand All @@ -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)
;
;
4 changes: 2 additions & 2 deletions src/Attribute/OnCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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));
}
}
}
4 changes: 2 additions & 2 deletions src/Attribute/OnEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
}
2 changes: 1 addition & 1 deletion src/TelegramBot/Command/ButtonSetCommandsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
4 changes: 2 additions & 2 deletions src/TelegramBot/Command/PolllingStartCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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] <error>TelegramApiException (%s) %s</error>',
$formattedDate,
$update->updateId,
Expand Down
8 changes: 4 additions & 4 deletions src/TelegramBot/Command/SetWebhookCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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');
}

Expand Down
8 changes: 4 additions & 4 deletions src/TelegramBot/Command/WebhookInfoCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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("<info>Webhook url:</info>\t\t%s", $webhookInfo->url));
$io->writeln(sprintf("<info>Max connections:</info>\t%s", $webhookInfo->maxConnections));
$io->writeln(sprintf("<info>Allowed updates:</info>\t%s", $allowedUpdates));
$io->writeln(\sprintf("<info>Webhook url:</info>\t\t%s", $webhookInfo->url));
$io->writeln(\sprintf("<info>Max connections:</info>\t%s", $webhookInfo->maxConnections));
$io->writeln(\sprintf("<info>Allowed updates:</info>\t%s", $allowedUpdates));

return Command::SUCCESS;
}
Expand Down
2 changes: 1 addition & 1 deletion src/TelegramBot/CommandMetadataProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/TelegramBot/Controller/WebHookController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/TelegramBot/LongPollingService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion src/TelegramBot/UpdateHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions src/config/compilerpass.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down
2 changes: 1 addition & 1 deletion src/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? '',
Expand Down
19 changes: 2 additions & 17 deletions tests/CommandMetadataProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,17 @@

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
{
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);
Expand All @@ -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));
}
}
2 changes: 1 addition & 1 deletion tests/TestKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
20 changes: 10 additions & 10 deletions tests/UpdateHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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');
Expand All @@ -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');
Expand All @@ -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');
Expand All @@ -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);
Expand All @@ -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);
Expand Down

0 comments on commit 0969b1e

Please sign in to comment.