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
4 changes: 4 additions & 0 deletions config/sets/symfony/symfony-code-quality.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Rector\Symfony\CodeQuality\Rector\ClassMethod\ParamTypeFromRouteRequiredRegexRector;
use Rector\Symfony\CodeQuality\Rector\ClassMethod\RemoveUnusedRequestParamRector;
use Rector\Symfony\CodeQuality\Rector\ClassMethod\ResponseReturnTypeControllerActionRector;
use Rector\Symfony\CodeQuality\Rector\ClassMethod\ReturnDirectJsonResponseRector;
use Rector\Symfony\CodeQuality\Rector\MethodCall\AssertSameResponseCodeWithDebugContentsRector;
use Rector\Symfony\CodeQuality\Rector\MethodCall\LiteralGetToRequestClassConstantRector;
use Rector\Symfony\CodeQuality\Rector\MethodCall\ParameterBagTypedGetMethodCallRector;
Expand Down Expand Up @@ -43,6 +44,9 @@
RequestIsMainRector::class,
ParameterBagTypedGetMethodCallRector::class,

// enable once tested
// ReturnDirectJsonResponseRector::class,

// tests
AssertSameResponseCodeWithDebugContentsRector::class,
StringCastDebugResponseRector::class,
Expand Down
7 changes: 6 additions & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# @todo enable
#includes:
# - vendor/symplify/phpstan-rules/config/symplify-rules.neon
# - vendor/symplify/phpstan-rules/config/rector-rules.neon

rules:
- Symplify\PHPStanRules\Rules\StringFileAbsolutePathExistsRule

Expand Down Expand Up @@ -65,4 +70,4 @@ parameters:
- '#Parameter 1 should use "PHPStan\\BetterReflection\\Reflection\\Adapter\\ReflectionMethod" type as the only type passed to this method#'

# local use php 8.3
- identifier: typeCoverage.constantTypeCoverage
- identifier: typeCoverage.constantTypeCoverage
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Rector\Symfony\Tests\CodeQuality\Rector\ClassMethod\ReturnDirectJsonResponseRector\Fixture;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;

final class SomeControllerClass extends AbstractController
{
public function index()
{
$jsonResponse = new JsonResponse();
$jsonResponse->setData([
'status' => 'ok',
]);

return $jsonResponse;
}
}

?>
-----
<?php

namespace Rector\Symfony\Tests\CodeQuality\Rector\ClassMethod\ReturnDirectJsonResponseRector\Fixture;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;

final class SomeControllerClass extends AbstractController
{
public function index()
{
return new \Symfony\Component\HttpFoundation\JsonResponse([
'status' => 'ok',
]);
}
}

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

declare(strict_types=1);

namespace Rector\Symfony\Tests\CodeQuality\Rector\ClassMethod\ReturnDirectJsonResponseRector;

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

final class ReturnDirectJsonResponseRectorTest 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\Symfony\CodeQuality\Rector\ClassMethod\ReturnDirectJsonResponseRector;

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

declare(strict_types=1);

namespace Rector\Symfony\CodeQuality\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use Rector\Rector\AbstractRector;
use Rector\Symfony\Bridge\NodeAnalyzer\ControllerMethodAnalyzer;
use Rector\Symfony\CodeQuality\Enum\ResponseClass;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Symfony\Tests\CodeQuality\Rector\ClassMethod\ReturnDirectJsonResponseRector\ReturnDirectJsonResponseRectorTest
*/
final class ReturnDirectJsonResponseRector extends AbstractRector
{
public function __construct(
private readonly ControllerMethodAnalyzer $controllerMethodAnalyzer,
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Instead of creating JsonResponse, setting items and data, return it directly at once to improve readability',
[
new CodeSample(
<<<'CODE_SAMPLE'
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class SomeController extends AbstractController
{
public function index()
{
$response = new JsonResponse();
$response->setData(['key' => 'value']);

return $response;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class SomeController extends AbstractController
{
public function index()
{
return new JsonResponse(['key' => 'value']);
}
}
CODE_SAMPLE
),
]
);
}

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

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

$jsonResponseVariable = null;
$assignStmtPosition = null;

$setDataExpr = null;
$setDataPosition = null;

foreach ((array) $node->stmts as $key => $stmt) {
if ($assignStmtPosition === null) {
$jsonResponseVariable = $this->matchNewJsonResponseAssignVariable($stmt);
if ($jsonResponseVariable instanceof Variable) {
$assignStmtPosition = $key;
continue;
}
}

if ($setDataPosition === null) {
if ($jsonResponseVariable instanceof Variable) {
$setDataExpr = $this->matchSetDataMethodCallExpr($stmt, $jsonResponseVariable);
if ($setDataExpr instanceof Expr) {
$setDataPosition = $key;
continue;
}
}
}

if (! $stmt instanceof Return_) {
continue;
}

// missing important data
if (! $jsonResponseVariable instanceof Variable || ! $setDataExpr instanceof Expr) {
continue;
}

if (! $this->nodeComparator->areNodesEqual($stmt->expr, $jsonResponseVariable)) {
continue;
}

$jsonResponseNew = new New_(new FullyQualified(ResponseClass::JSON), [new Arg($setDataExpr)]);

$stmt->expr = $jsonResponseNew;

// remove previous setData and assignment statements
unset($node->stmts[$assignStmtPosition], $node->stmts[$setDataPosition]);

// reindex statements
$node->stmts = array_values($node->stmts);

return $node;
}

return null;
}

private function matchNewJsonResponseAssignVariable(Stmt $stmt): ?Variable
{
if (! $stmt instanceof Expression) {
return null;
}

if (! $stmt->expr instanceof Assign) {
return null;
}

$assign = $stmt->expr;
if (! $assign->expr instanceof New_) {
return null;
}

if (! $this->isName($assign->expr->class, ResponseClass::JSON)) {
return null;
}

if (! $assign->var instanceof Variable) {
return null;
}

return $assign->var;
}

private function matchSetDataMethodCallExpr(Stmt $stmt, Variable $jsonResponseVariable): ?Expr
{
if (! $stmt instanceof Expression) {
return null;
}

if (! $stmt->expr instanceof MethodCall) {
return null;
}

$methodCall = $stmt->expr;
if (! $this->isName($methodCall->name, 'setData')) {
return null;
}

if (! $this->nodeComparator->areNodesEqual($methodCall->var, $jsonResponseVariable)) {
return null;
}

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

if ($methodCall->getArgs() === []) {
return null;
}

$soleArg = $methodCall->getArgs()[0];
return $soleArg->value;
}
}