Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CodeQuality] Add DateTimeToDateTimeInterfaceRector #4791

Merged
merged 6 commits into from
Dec 5, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions config/set/code-quality.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Rector\CodeQuality\Rector\BooleanNot\SimplifyDeMorganBinaryRector;
use Rector\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector;
use Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector;
use Rector\CodeQuality\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector;
use Rector\CodeQuality\Rector\Concat\JoinStringConcatRector;
use Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector;
use Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector;
Expand Down Expand Up @@ -163,4 +164,5 @@
$services->set(FixClassCaseSensitivityNameRector::class);
$services->set(IssetOnPropertyObjectToPropertyExistsRector::class);
$services->set(NewStaticToNewSelfRector::class);
$services->set(DateTimeToDateTimeInterfaceRector::class);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
<?php

declare(strict_types=1);

namespace Rector\CodeQuality\Rector\ClassMethod;

use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Type\NullType as PHPStanNullType;
use PHPStan\Type\ObjectType as PHPStanObjectType;
use PHPStan\Type\UnionType as PHPStanUnionType;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\NodeTypeResolver\NodeTypeResolver;

/**
* @see \Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\DateTimeToDateTimeInterfaceRectorTest
*/
final class DateTimeToDateTimeInterfaceRector extends AbstractRector
{
private const METHODS_MAP = [
Copy link
Member

@TomasVotruba TomasVotruba Dec 5, 2020

Choose a reason for hiding this comment

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

What kind of map is this? Excluded, included or ...?
More specific naming could help

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've renamed it to METHODS_RETURNING_CLASS_INSTANCE_MAP.

'add', 'modify', '__set_state', 'setDate', 'setISODate', 'setTime', 'setTimestamp', 'setTimezone', 'sub',
];

/**
* @var NodeTypeResolver
*/
private $nodeTypeResolver;

public function __construct(NodeTypeResolver $nodeTypeResolver)
{
$this->nodeTypeResolver = $nodeTypeResolver;
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Changes DateTime type-hint to DateTimeInterface', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass {
public function methodWithDateTime(\DateTime $dateTime)
{
return true;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass {
/**
* @param \DateTime|\DateTimeImmutable $dateTime
*/
public function methodWithDateTime(\DateTimeInterface $dateTime)
{
return true;
}
}
CODE_SAMPLE
),
]);
}

/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}

/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
$isModifiedNode = false;
simivar marked this conversation as resolved.
Show resolved Hide resolved
foreach ($node->getParams() as $param) {
if (! $this->isDateTimeParam($param)) {
continue;
}

$this->refactorParamTypeHint($param);
$this->refactorParamDocBlock($param, $node);
$this->refactorMethodCalls($param, $node);
$isModifiedNode = true;
}

if (! $isModifiedNode) {
return null;
}

return $node;
}

private function refactorParamTypeHint(Param $param): void
{
$dateTimeInterfaceType = new FullyQualified(DateTimeInterface::class);
if ($param->type instanceof NullableType) {
$param->type = new NullableType($dateTimeInterfaceType);
return;
}

$param->type = $dateTimeInterfaceType;
}

private function refactorParamDocBlock(Param $param, ClassMethod $classMethod): void
{
/** @var PhpDocInfo|null $phpDocInfo */
$phpDocInfo = $classMethod->getAttribute(AttributeKey::PHP_DOC_INFO);
if ($phpDocInfo === null) {
$phpDocInfo = $this->phpDocInfoFactory->createEmpty($classMethod);
}

$types = [new PHPStanObjectType(DateTime::class), new PHPStanObjectType(DateTimeImmutable::class)];
if ($param->type instanceof NullableType) {
$types[] = new PHPStanNullType();
}

$paramName = $this->getName($param->var);
if ($paramName === null) {
throw new ShouldNotHappenException();
}
$phpDocInfo->changeParamType(new PHPStanUnionType($types), $param, $paramName);
}

private function refactorMethodCalls(Param $param, ClassMethod $classMethod): void
{
if ($classMethod->stmts === null) {
return;
}

$this->traverseNodesWithCallable($classMethod->stmts, function (Node $node) use ($param) {
if (!($node instanceof MethodCall)){
return;
}

$this->refactorMethodCall($param, $node);
});
}

private function refactorMethodCall(Param $param, MethodCall $methodCall): void
{
$paramName = $this->getName($param->var);
if ($paramName === null || $this->shouldSkipMethodCallRefactor($paramName, $methodCall)) {
return;
}

$newAssignNode = new Assign(new Variable($paramName), $methodCall);

/** @var Node $parentNode */
$parentNode = $methodCall->getAttribute(AttributeKey::PARENT_NODE);
if ($parentNode instanceof Arg) {
$parentNode->value = $newAssignNode;
return;
}

$parentNode->expr = $newAssignNode;
}

private function shouldSkipMethodCallRefactor(string $paramName, MethodCall $methodCall): bool
{
if (! $this->isName($methodCall->var, $paramName)) {
return true;
}

if (! $this->isNames($methodCall->name, self::METHODS_MAP)) {
return true;
}

$parentNode = $methodCall->getAttribute(AttributeKey::PARENT_NODE) ;
if ($parentNode === null) {
return true;
}

return $parentNode instanceof Assign;
}

private function isDateTimeParam(Param $param): bool
{
return $this->nodeTypeResolver->isObjectTypeOrNullableObjectType($param, DateTime::class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector;

use Iterator;
use Rector\CodeQuality\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;

final class DateTimeToDateTimeInterfaceRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}

public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

protected function getRectorClass(): string
{
return DateTimeToDateTimeInterfaceRector::class;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

class FixtureFqn {
public function methodWithDateTime(\DateTime $dateTime)
{
return true;
}
}

?>
-----
<?php

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

class FixtureFqn {
/**
* @param \DateTime|\DateTimeImmutable $dateTime
*/
public function methodWithDateTime(\DateTimeInterface $dateTime)
{
return true;
}
}

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

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

class FixtureNullable {
public function methodWithDateTime(?\DateTime $dateTime)
{
return true;
}
}

?>
-----
<?php

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

class FixtureNullable {
/**
* @param \DateTime|\DateTimeImmutable|null $dateTime
*/
public function methodWithDateTime(?\DateTimeInterface $dateTime)
{
return true;
}
}

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

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

use \DateTime;

class FixtureUse {
public function methodWithDateTime(DateTime $dateTime)
{
return true;
}
}

?>
-----
<?php

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

use \DateTime;

class FixtureUse {
/**
* @param \DateTime|\DateTimeImmutable $dateTime
*/
public function methodWithDateTime(\DateTimeInterface $dateTime)
{
return true;
}
}

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

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

class FixtureVariableUsage {
/**
* @param mixed $mixed
*/
public function methodWithDateTime($mixed, \DateTime $dateTime)
{
$dateTime->modify('+1 day');

return $dateTime;
}
}

?>
-----
<?php

namespace Rector\CodeQuality\Tests\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector\Fixture;

class FixtureVariableUsage {
/**
* @param mixed $mixed
* @param \DateTime|\DateTimeImmutable $dateTime
*/
public function methodWithDateTime($mixed, \DateTimeInterface $dateTime)
{
$dateTime = $dateTime->modify('+1 day');

return $dateTime;
}
}

?>
Loading