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

[code-quality] Add NarrowUnusedSetUpDefinedPropertyRector #388

Merged
merged 2 commits into from
Nov 3, 2024
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
10 changes: 5 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@
"require-dev": {
"rector/rector-src": "dev-main",
"phpunit/phpunit": "^10.5",
"phpstan/phpstan": "^1.11",
"phpstan/phpstan": "^1.12",
"symplify/phpstan-rules": "^13.0",
"symplify/phpstan-extensions": "^11.2",
"symplify/phpstan-extensions": "^11.4",
"symplify/easy-coding-standard": "^12.3",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan-webmozart-assert": "^1.2",
"symplify/vendor-patches": "^11.2",
"tomasvotruba/class-leak": "^0.2",
"tracy/tracy": "^2.10",
"rector/type-perfect": "^0.2",
"rector/swiss-knife": "^0.2.35"
"tomasvotruba/class-leak": "^1.0",
"rector/type-perfect": "^1.0",
"rector/swiss-knife": "^1.0"
},
"autoload": {
"psr-4": {
Expand Down
3 changes: 3 additions & 0 deletions config/sets/phpunit-code-quality.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Rector\Config\RectorConfig;
use Rector\PHPUnit\CodeQuality\Rector\Class_\ConstructClassMethodToSetUpTestCaseRector;
use Rector\PHPUnit\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector;
use Rector\PHPUnit\CodeQuality\Rector\Class_\PreferPHPUnitThisCallRector;
use Rector\PHPUnit\CodeQuality\Rector\Class_\TestWithToDataProviderRector;
use Rector\PHPUnit\CodeQuality\Rector\Class_\YieldDataProviderRector;
Expand Down Expand Up @@ -51,6 +52,8 @@
NarrowSingleWillReturnCallbackRector::class,
SingleWithConsecutiveToWithRector::class,

NarrowUnusedSetUpDefinedPropertyRector::class,

// specific asserts
AssertCompareOnCountableWithMethodToAssertCountRector::class,
AssertCompareToSpecificMethodRector::class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Fixture;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Source\SomeType;

final class DefinedOnlyInSetup extends TestCase
{
private MockObject $someMock;

private MockObject $anotherMock;

protected function setUp(): void
{
$this->someMock = $this->createMock(SomeType::class);
$this->anotherMock = $this->createMock(SomeType::class);
}

public function test()
{
$this->anotherMock->expects($this->once());
}
}

?>
-----
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Fixture;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Source\SomeType;

final class DefinedOnlyInSetup extends TestCase
{
private MockObject $someMock;

protected function setUp(): void
{
$this->someMock = $this->createMock(SomeType::class);
$anotherMock = $this->createMock(SomeType::class);
}

public function test()
{
$this->anotherMock->expects($this->once());
}
}

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

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Fixture;

use PHPUnit\Framework\TestCase;
use Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Source\SomeType;

final class SkipNonMocks extends TestCase
{
private SomeType $someMock;
private SomeType $anotherMock;

protected function setUp(): void
{
$this->someMock = new SomeType();
$this->anotherMock = new SomeType();
}

public function test()
{
$this->anotherMock->expects($this->once());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector;

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

final class NarrowUnusedSetUpDefinedPropertyRectorTest 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,8 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Source;

final class SomeType
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\PHPUnit\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(NarrowUnusedSetUpDefinedPropertyRector::class);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php

declare(strict_types=1);

namespace Rector\PHPUnit\CodeQuality\Rector\Class_;

use PhpParser\Node;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
use PhpParser\NodeFinder;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\MethodName;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\NarrowUnusedSetUpDefinedPropertyRectorTest
*/
final class NarrowUnusedSetUpDefinedPropertyRector extends AbstractRector
{
/**
* @var string
*/
private const MOCK_OBJECT_CLASS = 'PHPUnit\Framework\MockObject\MockObject';

private readonly NodeFinder $nodeFinder;

public function __construct(
private readonly TestsNodeAnalyzer $testsNodeAnalyzer,
) {
$this->nodeFinder = new NodeFinder();
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Turn property used only in setUp() to variable', [
new CodeSample(
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;

class SomeServiceTest extends TestCase
{
private $someServiceMock;

public function setUp(): void
{
$this->someServiceMock = $this->createMock(SomeService::class);
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;

class SomeServiceTest extends TestCase
{
public function setUp(): void
{
$someServiceMock = $this->createMock(SomeService::class);
}
}
CODE_SAMPLE
,
),
]);
}

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

/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->testsNodeAnalyzer->isInTestClass($node)) {
return null;
}

$setUpClassMethod = $node->getMethod(MethodName::SET_UP);
if (! $setUpClassMethod instanceof ClassMethod) {
return null;
}

$hasChanged = false;

foreach ($node->stmts as $key => $classStmt) {
if (! $classStmt instanceof Property) {
continue;
}

$property = $classStmt;
if (! $property->type instanceof Name) {
continue;
}

if (! $this->isName($property->type, self::MOCK_OBJECT_CLASS)) {
continue;
}

if (! $this->isPropertyUsedOutsideSetUpClassMethod($node, $setUpClassMethod, $property)) {
continue;
}
Comment on lines +111 to +113
Copy link
Member

Choose a reason for hiding this comment

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

the check is flipped, continue should check when property is used

Copy link
Member

Choose a reason for hiding this comment

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

ok, it seems fixed at f24bef5


$hasChanged = true;

unset($node->stmts[$key]);
$propertyName = $property->props[0]->name->toString();

// change property to variable in setUp() method
$this->traverseNodesWithCallable($setUpClassMethod, function (Node $node) use (
$propertyName
): ?Variable {
if (! $node instanceof PropertyFetch) {
return null;
}

if (! $this->isName($node->var, 'this')) {
return null;
}

if (! $this->isName($node->name, $propertyName)) {
return null;
}

return new Variable($propertyName);
});
}

if ($hasChanged) {
return $node;
}

return null;
}

private function isPropertyUsedOutsideSetUpClassMethod(
Class_ $class,
ClassMethod $setUpClassMethod,
Property $property
): bool {
$isPropertyUsed = false;

foreach ($class->getMethods() as $classMethod) {
// skip setUp() method
if ($classMethod === $setUpClassMethod) {
continue;
}

// check if property is used anywhere else than setup
$usedPropertyFetch = $this->nodeFinder->findFirst($classMethod, function (Node $node) use (
$property
): bool {
if (! $node instanceof PropertyFetch) {
return false;
}

if (! $this->isName($node->var, 'this')) {
return false;
}

$propertyName = $property->props[0]->name->toString();
return $this->isName($node->name, $propertyName);
});

if ($usedPropertyFetch instanceof PropertyFetch) {
$isPropertyUsed = true;
}
}

return $isPropertyUsed;
}
}
Loading