Skip to content

Commit

Permalink
[CodeQuality] Skip Child class of \DateTime on DateTimeToDateTimeInte…
Browse files Browse the repository at this point in the history
…rfaceRector (#703)

* Add failing test fixture for DateTimeToDateTimeInterfaceRector

Relates to #6641

* Change order of namespace and imports

Previous one was generated by Rector's Demo.

Co-authored-by: Abdul Malik Ikhsan <samsonasik@gmail.com>

* Do not force \DateTimeInterface for args based on \DateTime child classes

* Rename fixture file name

* Add more tests for skipping refactorization

Co-authored-by: Abdul Malik Ikhsan <samsonasik@gmail.com>
  • Loading branch information
Wirone and samsonasik committed Aug 17, 2021
1 parent 91ac830 commit c1b7a97
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

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

use DateTime as PhpDateTime;

class DateTime extends PhpDateTime
{
public function getDateTimeCustomFormat(): ?string
{
return $this->format('Y-m-d H:i:s');
}
}

class Foo
{
public static function bar(?DateTime $datetime)
{
// ...
}

public static function baz(DateTime $datetime)
{
// ...
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

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

use stdClass;

class SkipDifferentType
{
public static function run(stdClass $stdClass)
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

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

class SkipNoType
{
public static function run($param)
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

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

use DateTime;
use DateTimeImmutable;

class SkipUnionType
{
public function run(DateTime|DateTimeImmutable $dateTime)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,16 @@ public function getNodeTypes(): array
public function refactor(Node $node): ?Node
{
$isModifiedNode = false;
$dateTimeObject = new ObjectType('DateTime');

foreach ($node->getParams() as $param) {
if (! $this->isObjectType($param, new ObjectType('DateTime'))) {
if (! $this->isObjectType($param, $dateTimeObject)) {
continue;
}

// Do not refactor if node's type is a child class of \DateTime (can have wider API)
$paramType = $this->nodeTypeResolver->resolve($param);
if (!$paramType->isSuperTypeOf($dateTimeObject)->yes()) {
continue;
}

Expand Down

0 comments on commit c1b7a97

Please sign in to comment.