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
3 changes: 3 additions & 0 deletions config/sets/phpunit-code-quality.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@
NarrowSingleWillReturnCallbackRector::class,
SingleWithConsecutiveToWithRector::class,

// enable once better tested
// WillReturnCallbackFallbackToThrowRector::class,

// type declarations
TypeWillReturnCallableArrowFunctionRector::class,
StringCastAssertStringContainsStringRector::class,
Expand Down
2 changes: 1 addition & 1 deletion config/sets/phpunit-mock-to-stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

use Rector\Config\RectorConfig;
use Rector\PHPUnit\CodeQuality\Rector\Class_\AddIntersectionVarToMockObjectPropertyRector;
use Rector\PHPUnit\CodeQuality\Rector\ClassMethod\BareCreateMockAssignToDirectUseRector;
use Rector\PHPUnit\CodeQuality\Rector\Class_\AddStubIntersectionVarToStubPropertyRector;
use Rector\PHPUnit\CodeQuality\Rector\ClassMethod\BareCreateMockAssignToDirectUseRector;
use Rector\PHPUnit\PHPUnit120\Rector\CallLike\CreateStubInCoalesceArgRector;
use Rector\PHPUnit\PHPUnit120\Rector\CallLike\CreateStubOverCreateMockArgRector;
use Rector\PHPUnit\PHPUnit120\Rector\Class_\PropertyCreateMockToCreateStubRector;
Expand Down
2 changes: 1 addition & 1 deletion config/sets/phpunit100.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
// https://github.com/sebastianbergmann/phpunit/pull/3687
new MethodCallRename('PHPUnit\Framework\MockObject\MockBuilder', 'setMethods', 'onlyMethods'),

//https://github.com/sebastianbergmann/phpunit/issues/5062
// https://github.com/sebastianbergmann/phpunit/issues/5062
new MethodCallRename('PHPUnit\Framework\TestCase', 'expectDeprecationMessage', 'expectExceptionMessage'),
new MethodCallRename(
'PHPUnit\Framework\TestCase',
Expand Down
2 changes: 1 addition & 1 deletion ecs.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Symplify\EasyCodingStandard\Config\ECSConfig;

return ECSConfig::configure()
->withPreparedSets(psr12: true, common: true, symplify: true)
->withPreparedSets(psr12: true, common: true)
->withPaths([
__DIR__ . '/src',
__DIR__ . '/rules',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\MethodCall\WillReturnCallbackFallbackToThrowRector\Fixture;

use PHPUnit\Framework\TestCase;

final class SkipFallbackReturn extends TestCase
{
public function test()
{
$matcher = $this->exactly(2);

$someServiceMock = $this->createMock(SomeMockedClass::class);
$someServiceMock->expects($matcher)
->method('run')
->willReturnCallback(function () use ($matcher) {
if ($matcher->numberOfInvocations() === 1) {
return 'first';
}

if ($matcher->numberOfInvocations() === 2) {
return 'second';
}

return 'third';
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\MethodCall\WillReturnCallbackFallbackToThrowRector\Fixture;

use PHPUnit\Framework\TestCase;

final class SkipNoMatcherBranch extends TestCase
{
public function test()
{
$matcher = $this->exactly(1);

$someServiceMock = $this->createMock(SomeMockedClass::class);
$someServiceMock->expects($matcher)
->method('run')
->willReturnCallback(function () use ($matcher) {
return 'value';
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\MethodCall\WillReturnCallbackFallbackToThrowRector\Fixture;

use PHPUnit\Framework\TestCase;

final class VoidFallback extends TestCase
{
public function test()
{
$matcher = $this->exactly(1);

$someServiceMock = $this->createMock(SomeMockedClass::class);
$someServiceMock->expects($matcher)
->method('run')
->willReturnCallback(function () use ($matcher) {
if ($matcher->numberOfInvocations() === 1) {
return 'first';
}
});
}
}

?>
-----
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\MethodCall\WillReturnCallbackFallbackToThrowRector\Fixture;

use PHPUnit\Framework\TestCase;

final class VoidFallback extends TestCase
{
public function test()
{
$matcher = $this->exactly(1);

$someServiceMock = $this->createMock(SomeMockedClass::class);
$someServiceMock->expects($matcher)
->method('run')
->willReturnCallback(function () use ($matcher) {
if ($matcher->numberOfInvocations() === 1) {
return 'first';
}
throw new \PHPUnit\Framework\Exception(sprintf('Method should not be called for the %dth time', $matcher->numberOfInvocations()));
});
}
}

?>
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\MethodCall\WillReturnCallbackFallbackToThrowRector;

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

final class WillReturnCallbackFallbackToThrowRectorTest 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,10 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\PHPUnit\CodeQuality\Rector\MethodCall\WillReturnCallbackFallbackToThrowRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(WillReturnCallbackFallbackToThrowRector::class);
};
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private function refactorClassMethod(Class_ $class, ClassMethod $classMethod): v
$arrayItemsSingleLine[] = new ArrayItem($this->createArrayItem($values[0]));
}

//cleanup
// cleanup
if ($this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $testWithPhpDocTagNode)) {
$this->hasChanged = true;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
<?php

declare(strict_types=1);

namespace Rector\PHPUnit\CodeQuality\Rector\MethodCall;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\ClosureUse;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Throw_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use Rector\PHPUnit\Enum\ConsecutiveVariable;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Rector\PHPUnit\NodeFactory\MatcherInvocationCountMethodCallNodeFactory;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\PHPUnit\Tests\CodeQuality\Rector\MethodCall\WillReturnCallbackFallbackToThrowRector\WillReturnCallbackFallbackToThrowRectorTest
*/
final class WillReturnCallbackFallbackToThrowRector extends AbstractRector
{
public function __construct(
private readonly TestsNodeAnalyzer $testsNodeAnalyzer,
private readonly MatcherInvocationCountMethodCallNodeFactory $matcherInvocationCountMethodCallNodeFactory,
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Add a throw fallback to a consecutive willReturnCallback() that has no explicit fallback return, so an unexpected extra call fails loudly',
[
new CodeSample(
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;

final class SomeTest extends TestCase
{
public function test()
{
$matcher = $this->exactly(1);

$this->someServiceMock->expects($matcher)
->method('run')
->willReturnCallback(function () use ($matcher) {
if ($matcher->numberOfInvocations() === 1) {
return 1;
}
});
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;

final class SomeTest extends TestCase
{
public function test()
{
$matcher = $this->exactly(1);

$this->someServiceMock->expects($matcher)
->method('run')
->willReturnCallback(function () use ($matcher) {
if ($matcher->numberOfInvocations() === 1) {
return 1;
}

throw new \PHPUnit\Framework\Exception(sprintf('Method should not be called for the %dth time', $matcher->numberOfInvocations()));
});
}
}
CODE_SAMPLE
),
]
);
}

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

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

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

if ($node->isFirstClassCallable()) {
return null;
}

if (count($node->getArgs()) !== 1) {
return null;
}

$closure = $node->getArgs()[0]
->value;
if (! $closure instanceof Closure) {
return null;
}

if (! $this->usesMatcher($closure)) {
return null;
}

// the closure must branch on the matcher invocation count first
if (! $this->hasConsecutiveIf($closure)) {
return null;
}

$lastStmt = $closure->stmts[array_key_last($closure->stmts)] ?? null;

// the last statement must be an if branch; an explicit fallback "return <expr>;" is left untouched
if (! $lastStmt instanceof If_) {
return null;
}

$closure->stmts[] = $this->createThrow();

return $node;
}

private function usesMatcher(Closure $closure): bool
{
return array_any(
$closure->uses,
fn (ClosureUse $use): bool => $this->isName($use->var, ConsecutiveVariable::MATCHER)
);
}

private function hasConsecutiveIf(Closure $closure): bool
{
foreach ($closure->stmts as $stmt) {
if (! $stmt instanceof If_) {
continue;
}

$hasMatcherCall = false;
$this->traverseNodesWithCallable($stmt->cond, function (Node $node) use (&$hasMatcherCall): null {
if ($node instanceof MethodCall
&& $node->var instanceof Variable
&& $this->isName($node->var, ConsecutiveVariable::MATCHER)
) {
$hasMatcherCall = true;
}

return null;
});

if ($hasMatcherCall) {
return true;
}
}

return false;
}

private function createThrow(): Expression
{
$sprintfFuncCall = $this->nodeFactory->createFuncCall('sprintf', [
new String_('Method should not be called for the %dth time'),
$this->matcherInvocationCountMethodCallNodeFactory->create(),
]);

$new = new New_(new FullyQualified('PHPUnit\Framework\Exception'), [new Arg($sprintfFuncCall)]);

return new Expression(new Throw_($new));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,14 @@ public function refactor(Node $node): ?Node
return null;
}

//when less then 5 arguments given: do nothing
// when less then 5 arguments given: do nothing
if (! isset($node->getArgs()[4])) {
return null;
}

$fourthArg = $node->getArgs()[4];

//when 5th argument check identity is true: do nothing
// when 5th argument check identity is true: do nothing
if ($this->valueResolver->isValue($fourthArg->value, true)) {
return null;
}
Expand Down
Loading
Loading