Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamStringTypeFromSprintfUseRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class AddParamStringTypeFromSprintfUseRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamStringTypeFromSprintfUseRector\Fixture;

final class PassSprintf
{
public function test($name)
{
return sprintf('Hello %s', $name);
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamStringTypeFromSprintfUseRector\Fixture;

final class PassSprintf
{
public function test(string $name)
{
return sprintf('Hello %s', $name);
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamStringTypeFromSprintfUseRector\Fixture;

final class SkipNonStringMask
{
public function test($name)
{
return sprintf('Hello %d', $name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

use Rector\TypeDeclaration\Rector\ClassMethod\AddParamStringTypeFromSprintfUseRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(AddParamStringTypeFromSprintfUseRector::class);
};

This file was deleted.

9 changes: 0 additions & 9 deletions rules/Privatization/TypeManipulator/TypeNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,6 @@ public function __construct(

}

/**
* @deprecated This method is deprecated and will be removed in the next major release.
* Use @see generalizeConstantTypes() instead.
*/
public function generalizeConstantBoolTypes(Type $type): Type
{
return $this->generalizeConstantTypes($type);
}

/**
* Generalize false/true constantArrayType to bool,
* as mostly default value but accepts both
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclaration\NodeAnalyzer;

use Nette\Utils\Strings;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\PhpParser\Node\BetterNodeFinder;

final readonly class VariableInSprintfMaskMatcher
{
public function __construct(
private BetterNodeFinder $betterNodeFinder,
private NodeNameResolver $nodeNameResolver,
) {

}

public function matchMask(ClassMethod|Function_ $functionLike, string $variableName, string $mask): bool
{
$funcCalls = $this->betterNodeFinder->findInstancesOfScoped((array) $functionLike->stmts, FuncCall::class);

foreach ($funcCalls as $funcCall) {
if (! $this->nodeNameResolver->isName($funcCall->name, 'sprintf')) {
continue;
}

if ($funcCall->isFirstClassCallable()) {
continue;
}

$args = $funcCall->getArgs();
if (count($args) < 2) {
continue;
}

/** @var Arg $messageArg */
$messageArg = array_shift($args);
if (! $messageArg->value instanceof String_) {
continue;
}

$string = $messageArg->value;

// match all %s, %d types by position
$masks = Strings::match($string->value, '#%[sd]#');

foreach ($args as $position => $arg) {
if (! $arg->value instanceof Variable) {
continue;
}

if (! $this-> nodeNameResolver->isName($arg->value, $variableName)) {
continue;
}

if (! isset($masks[$position])) {
continue;
}

$knownMaskOnPosition = $masks[$position];
if ($knownMaskOnPosition !== $mask) {
continue;
}

return true;
}
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclaration\Rector\ClassMethod;

use PhpParser\Node\Identifier;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use Rector\Rector\AbstractRector;
use Rector\TypeDeclaration\NodeAnalyzer\VariableInSprintfMaskMatcher;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamStringTypeFromSprintfUseRector\AddParamStringTypeFromSprintfUseRectorTest
*/
final class AddParamStringTypeFromSprintfUseRector extends AbstractRector
{
public function __construct(
private readonly VariableInSprintfMaskMatcher $variableInSprintfMaskMatcher,
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Add string type to parameters used in sprintf calls',
[
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function formatMessage($name)
{
return sprintf('My name is %s', $name);
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function formatMessage(string $name)
{
return sprintf('My name is %s', $name);
}
}
CODE_SAMPLE
)]
);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class, Function_::class];
}

/**
* @param ClassMethod|Function_ $node
*/
public function refactor(Node $node): ClassMethod|Function_|null
{
if ($node->stmts === null) {
return null;
}

if ($node->getParams() === []) {
return null;
}

$hasChanged = false;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check parent method exists guard is needed here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

foreach ($node->getParams() as $param) {
if ($param->type instanceof Node) {
continue;
}

/** @var string $variableName */
$variableName = $this->getName($param->var);

if (! $this->variableInSprintfMaskMatcher->matchMask($node, $variableName, '%s')) {
continue;
}

$param->type = new Identifier('string');
$hasChanged = true;
}

if (! $hasChanged) {
return null;
}

return $node;
}
}
2 changes: 2 additions & 0 deletions src/Config/Level/TypeDeclarationLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Rector\TypeDeclaration\Rector\Class_\TypedPropertyFromJMSSerializerAttributeTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamStringTypeFromSprintfUseRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeBasedOnPHPUnitDataProviderRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeFromPropertyTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationBasedOnParentClassMethodRector;
Expand Down Expand Up @@ -148,6 +149,7 @@ final class TypeDeclarationLevel
// array parameter from dim fetch assign inside
StrictArrayParamDimFetchRector::class,
AddParamFromDimFetchKeyUseRector::class,
AddParamStringTypeFromSprintfUseRector::class,

// possibly based on docblocks, but also helpful, intentionally last
AddArrayFunctionClosureParamTypeRector::class,
Expand Down