Skip to content
Closed
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
1 change: 1 addition & 0 deletions config/set/coding-style/coding-style.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ services:
Rector\CodingStyle\Rector\ClassConst\VarConstantCommentRector: ~
Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector: ~
Rector\CodingStyle\Rector\ClassMethod\NewlineBeforeNewAssignSetRector: ~
Rector\CodingStyle\Rector\String_\ManualJsonStringToJsonEncodeArrayRector: ~
4 changes: 4 additions & 0 deletions ecs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,7 @@ parameters:
Symplify\CodingStandard\Sniffs\DependencyInjection\NoClassInstantiationSniff:
# 3rd party api
- 'src/PhpParser/Node/Value/ValueResolver.php'

PhpCsFixer\Fixer\PhpUnit\PhpUnitStrictFixer:
# intentional equals
- 'tests/PhpParser/Node/NodeFactoryTest.php'
59 changes: 59 additions & 0 deletions packages/CodingStyle/src/Node/ConcatJoiner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php declare(strict_types=1);

namespace Rector\CodingStyle\Node;

use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PhpParser\Node\Scalar\String_;
use Rector\NodeTypeResolver\Node\AttributeKey;

final class ConcatJoiner
{
/**
* @var string
*/
private $content;

/**
* @var Expr[]
*/
private $placeholderNodes = [];

/**
* Joins all String_ nodes to string.
* Returns that string + array of non-string nodes that were replaced by hash placeholders
*
* @return string[]|Expr[][]
*/
public function joinToStringAndPlaceholderNodes(Concat $concat): array
{
if (! $concat->getAttribute(AttributeKey::PARENT_NODE) instanceof Concat) {
$this->reset();
}

$this->processConcatSide($concat->left);
$this->processConcatSide($concat->right);

return [$this->content, $this->placeholderNodes];
}

private function processConcatSide(Expr $expr): void
{
if ($expr instanceof String_) {
$this->content .= $expr->value;
} elseif ($expr instanceof Concat) {
$this->joinToStringAndPlaceholderNodes($expr);
} else {
$objectHash = spl_object_hash($expr);
$this->placeholderNodes[$objectHash] = $expr;

$this->content .= $objectHash;
}
}

private function reset(): void
{
$this->content = '';
$this->placeholderNodes = [];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
<?php declare(strict_types=1);

namespace Rector\CodingStyle\Rector\String_;

use Nette\Utils\Json;
use Nette\Utils\JsonException;
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Scalar\String_;
use Rector\CodingStyle\Node\ConcatJoiner;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;

/**
* @see \Rector\CodingStyle\Tests\Rector\String_\ManualJsonStringToJsonEncodeArrayRector\ManualJsonStringToJsonEncodeArrayRectorTest
*/
final class ManualJsonStringToJsonEncodeArrayRector extends AbstractRector
{
/**
* @var ConcatJoiner
*/
private $concatJoiner;

public function __construct(ConcatJoiner $concatJoiner)
{
$this->concatJoiner = $concatJoiner;
}

public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Add extra space before new assign set', [
new CodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
public function run()
{
$someJsonAsString = '{"role_name":"admin","numberz":{"id":"10"}}';
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
public function run()
{
$data = [
'role_name' => 'admin',
'numberz' => ['id' => 10]
];

$someJsonAsString = json_encode($data);
}
}
CODE_SAMPLE
),
]);
}

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

/**
* @param Assign $node
*/
public function refactor(Node $node): ?Node
{
if ($node->expr instanceof String_) {
$stringValue = $node->expr->value;

// A. full json string
$isJsonString = $this->isJsonString($stringValue);
if ($isJsonString) {
return $this->processJsonString($node, $stringValue);
}

// B. just start of a json?
$currentNode = $node;

/** @var Expr[] $placeholderNodes */
$placeholderNodes = [];
$nodesToRemove = [];
$content = '';

while ($nextExpressionNode = $this->matchNextExpressionAssignConcatToSameVariable(
$node->var,
$currentNode
)) {
if ($nextExpressionNode->expr instanceof String_) {
$content .= $nextExpressionNode->expr->value;
} elseif ($nextExpressionNode->expr instanceof Concat) {
[$newContent, $placeholderNodes] = $this->concatJoiner->joinToStringAndPlaceholderNodes(
$nextExpressionNode->expr
);
$content .= $newContent;
} elseif ($nextExpressionNode->expr instanceof Expr) {
$objectHash = spl_object_hash($nextExpressionNode->expr);
$placeholderNodes[$objectHash] = $nextExpressionNode->expr;
$content .= $objectHash;
}

$nodesToRemove[] = $nextExpressionNode;

// jump to next one
$currentNode = $this->getNextExpression($currentNode);
if ($currentNode === null) {
break;
}
}

/** @var string $content */
$stringValue .= $content;
if (! $this->isJsonString($stringValue)) {
return null;
}

// remove nodes
$this->removeNodes($nodesToRemove);

$array = Json::decode($stringValue, Json::FORCE_ARRAY);

$jsonArray = $this->createArray($array);

/** @var Expr[] $placeholderNodes */
$this->replaceNodeObjectHashPlaceholdersWithNodes($jsonArray, $placeholderNodes);

return $this->createAndReturnJsonEncodeFromArray($node, $jsonArray);
}

if ($node->expr instanceof Concat) {
// process only first concat
$concatParentNode = $node->getAttribute(AttributeKey::PARENT_NODE);
if ($concatParentNode instanceof Concat) {
return null;
}

/** @var string $content */
/** @var Expr[] $placeholderNodes */
[$content, $placeholderNodes] = $this->concatJoiner->joinToStringAndPlaceholderNodes($node->expr);

if (! $this->isJsonString($content)) {
return null;
}

$array = Json::decode($content, Json::FORCE_ARRAY);

$jsonArray = $this->createArray($array);

$this->replaceNodeObjectHashPlaceholdersWithNodes($jsonArray, $placeholderNodes);

return $this->createAndReturnJsonEncodeFromArray($node, $jsonArray);
}

return null;
}

private function processJsonString(Assign $assign, string $stringValue): Node
{
$array = Json::decode($stringValue, Json::FORCE_ARRAY);
$arrayNode = $this->createArray($array);

return $this->createAndReturnJsonEncodeFromArray($assign, $arrayNode);
}

private function isJsonString(string $stringValue): bool
{
if (! (bool) Strings::match($stringValue, '#{(.*?\:.*?)}#')) {
return false;
}

try {
return (bool) Json::decode($stringValue, Json::FORCE_ARRAY);
} catch (JsonException $jsonException) {
return false;
}
}

private function createAndReturnJsonEncodeFromArray(Assign $assign, Array_ $jsonArray): Assign
{
$jsonDataVariable = new Variable('jsonData');

$jsonDataAssign = new Assign($jsonDataVariable, $jsonArray);
$this->addNodeBeforeNode($jsonDataAssign, $assign);

$assign->expr = $this->createStaticCall('Nette\Utils\Json', 'encode', [$jsonDataVariable]);

return $assign;
}

/**
* @param Expr[] $placeholderNodes
*/
private function replaceNodeObjectHashPlaceholdersWithNodes(Array_ $array, array $placeholderNodes): void
{
// traverse and replace placeholdes by original nodes
$this->traverseNodesWithCallable([$array], function (Node $node) use ($placeholderNodes): ?Expr {
if (! $node instanceof String_) {
return null;
}

$stringValue = $node->value;

return $placeholderNodes[$stringValue] ?? null;
});
}

/**
* @param Assign|Expr\AssignOp\Concat $currentNode
*/
private function matchNextExpressionAssignConcatToSameVariable(Expr $expr, Node $currentNode): ?Expr\AssignOp\Concat
{
$nextExpression = $this->getNextExpression($currentNode);
if (! $nextExpression instanceof Node\Stmt\Expression) {
return null;
}

$nextExpressionNode = $nextExpression->expr;
if (! $nextExpressionNode instanceof Expr\AssignOp\Concat) {
return null;
}

// is assign to same variable?
if (! $this->areNodesEqual($expr, $nextExpressionNode->var)) {
return null;
}

return $nextExpressionNode;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Rector\CodingStyle\Tests\Rector\String_\ManualJsonStringToJsonEncodeArrayRector\Fixture;

final class ConcatJson
{
public function run()
{
$someJsonAsString = '{"role_name":"admin","numberz":{"id":"' . 5 . '"}}';
}
}

?>
-----
<?php

namespace Rector\CodingStyle\Tests\Rector\String_\ManualJsonStringToJsonEncodeArrayRector\Fixture;

final class ConcatJson
{
public function run()
{
$jsonData = ['role_name' => 'admin', 'numberz' => ['id' => 5]];
$someJsonAsString = \Nette\Utils\Json::encode($jsonData);
}
}

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

namespace Rector\CodingStyle\Tests\Rector\String_\ManualJsonStringToJsonEncodeArrayRector\Fixture;

final class SomeClass
{
public function run()
{
$someJsonAsString = '{"role_name":"admin","numberz":{"id":"10"}}';
}
}

?>
-----
<?php

namespace Rector\CodingStyle\Tests\Rector\String_\ManualJsonStringToJsonEncodeArrayRector\Fixture;

final class SomeClass
{
public function run()
{
$jsonData = ['role_name' => 'admin', 'numberz' => ['id' => '10']];
$someJsonAsString = \Nette\Utils\Json::encode($jsonData);
}
}

?>
Loading