Skip to content

Commit

Permalink
fix: PhpdocToReturnTypeFixerTest - support for arrow functions (PHP-C…
Browse files Browse the repository at this point in the history
  • Loading branch information
keradus authored Jan 9, 2024
1 parent 27ad94d commit c5cde0c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
namespace PhpCsFixer\Fixer\FunctionNotation;

use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
Expand Down Expand Up @@ -153,8 +152,7 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
continue;
}

/** @var Annotation $returnTypeAnnotation */
$returnTypeAnnotation = current($returnTypeAnnotations);
$returnTypeAnnotation = $returnTypeAnnotations[0];

$typesExpression = $returnTypeAnnotation->getTypeExpression();

Expand Down Expand Up @@ -185,20 +183,21 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
continue;
}

$startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']);
$paramsStartIndex = $tokens->getNextTokenOfKind($index, ['(']);
$paramsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $paramsStartIndex);

if ($this->hasReturnTypeHint($tokens, $startIndex)) {
$bodyStartIndex = $tokens->getNextTokenOfKind($paramsEndIndex, ['{', ';', [T_DOUBLE_ARROW]]);

if ($this->hasReturnTypeHint($tokens, $bodyStartIndex)) {
continue;
}

if (!$this->isValidSyntax(sprintf(self::TYPE_CHECK_TEMPLATE, $returnType))) {
continue;
}

$endFuncIndex = $tokens->getPrevTokenOfKind($startIndex, [')']);

$tokens->insertAt(
$endFuncIndex + 1,
$paramsEndIndex + 1,
array_merge(
[
new Token([CT::T_TYPE_COLON, ':']),
Expand Down
26 changes: 26 additions & 0 deletions tests/Fixer/FunctionNotation/PhpdocToReturnTypeFixerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,32 @@ function bar() {}
'<?php /** @return int */ fn(): int => 1;',
'<?php /** @return int */ fn() => 1;',
];

yield 'arrow function (static)' => [
'<?php /** @return int */ static fn(): int => 1;',
'<?php /** @return int */ static fn() => 1;',
];

yield 'arrow function (as argument ended with ,)' => [
'<?php
Utils::stableSort(
$elements,
/**
* @return array
*/
static fn($a): array => [$a],
fn($a, $b) => 1,
);',
'<?php
Utils::stableSort(
$elements,
/**
* @return array
*/
static fn($a) => [$a],
fn($a, $b) => 1,
);',
];
}

/**
Expand Down

0 comments on commit c5cde0c

Please sign in to comment.