From 3d84859dcc8cb81749774b2d98de938d693603ba Mon Sep 17 00:00:00 2001 From: Leo Feyer <1192057+leofeyer@users.noreply.github.com> Date: Mon, 29 Jan 2024 09:46:42 +0100 Subject: [PATCH] Handle anonymous functions in the type hint order fixer --- src/Fixer/TypeHintOrderFixer.php | 10 ++++++++-- tests/Fixer/TypeHintOrderFixerTest.php | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Fixer/TypeHintOrderFixer.php b/src/Fixer/TypeHintOrderFixer.php index 8236d8b..9a45944 100644 --- a/src/Fixer/TypeHintOrderFixer.php +++ b/src/Fixer/TypeHintOrderFixer.php @@ -61,7 +61,7 @@ public function __construct( public function isCandidate(Tokens $tokens): bool { - return $tokens->isAnyTokenKindsFound([T_PUBLIC, T_PROTECTED, T_PRIVATE]); + return $tokens->isAnyTokenKindsFound([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FUNCTION, T_FN]); } /** @@ -75,7 +75,13 @@ public function getPriority(): int protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { - if (!$tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE])) { + if (!$tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FUNCTION, T_FN])) { + continue; + } + + // Anonymous functions + if ($tokens[$index]->isGivenKind([T_FUNCTION, T_FN])) { + $index = $this->handleFunction($tokens, $index); continue; } diff --git a/tests/Fixer/TypeHintOrderFixerTest.php b/tests/Fixer/TypeHintOrderFixerTest.php index 31dad37..17ec116 100644 --- a/tests/Fixer/TypeHintOrderFixerTest.php +++ b/tests/Fixer/TypeHintOrderFixerTest.php @@ -52,6 +52,13 @@ public function __construct( public function bar(object|FooService|BarService $service, iterable|int $count): null|string|int { + $foo = function (string|int $id): ?FooService { + }; + + $foo = function (string|int $id) use ($count): ?FooService { + }; + + $bar = fn (string|int $id): ?FooService => null; } } EOT, @@ -73,6 +80,13 @@ public function __construct( public function bar(BarService|FooService|object $service, int|iterable $count): int|string|null { + $foo = function (int|string $id): FooService|null { + }; + + $foo = function (int|string $id) use ($count): FooService|null { + }; + + $bar = fn (int|string $id): FooService|null => null; } } EOT,