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
17 changes: 11 additions & 6 deletions rules/Php73/Rector/FuncCall/JsonThrowOnErrorRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\BitwiseOr;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Identifier;
Expand All @@ -26,9 +27,10 @@
*/
final class JsonThrowOnErrorRector extends AbstractRector implements MinPhpVersionInterface
{
private bool $hasChanged = false;
private const array FLAGS = ['JSON_THROW_ON_ERROR'];

private bool $hasChanged = false;

public function __construct(
private readonly ValueResolver $valueResolver,
private readonly BetterNodeFinder $betterNodeFinder
Expand Down Expand Up @@ -140,11 +142,13 @@ private function processJsonEncode(FuncCall $funcCall): FuncCall
$arg = $funcCall->args[1];
$flags = $this->getFlags($arg);
}

$newArg = $this->getArgWithFlags($flags);
if ($newArg instanceof Arg) {
$this->hasChanged = true;
$funcCall->args[1] = $newArg;
}

return $funcCall;
}

Expand All @@ -171,6 +175,7 @@ private function processJsonDecode(FuncCall $funcCall): FuncCall
$this->hasChanged = true;
$funcCall->args[3] = $newArg;
}

return $funcCall;
}

Expand Down Expand Up @@ -213,10 +218,11 @@ private function getFlags(Expr|Arg $arg, array $flags = []): array
}

// Multiple flags: FLAG_A | FLAG_B | FLAG_C
if ($arg instanceof Node\Expr\BinaryOp\BitwiseOr) {
if ($arg instanceof BitwiseOr) {
$flags = $this->getFlags($arg->left, $flags);
$flags = $this->getFlags($arg->right, $flags);
}

return array_values(array_unique($flags)); // array_unique in case the same flag is written multiple times
}

Expand All @@ -230,18 +236,17 @@ private function getArgWithFlags(array $flags): ?Arg
if ($originalCount === count($flags)) {
return null;
}

// Single flag
if (count($flags) === 1) {
return new Arg($this->createConstFetch($flags[0]));
}

// Build FLAG_A | FLAG_B | FLAG_C
$expr = $this->createConstFetch(array_shift($flags));

foreach ($flags as $flag) {
$expr = new Node\Expr\BinaryOp\BitwiseOr(
$expr,
$this->createConstFetch($flag)
);
$expr = new BitwiseOr($expr, $this->createConstFetch($flag));
}

return new Arg($expr);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,11 +333,6 @@ public function processNodes(
return;
}

if ($node instanceof ArrayItem) {
$this->processArrayItem($node, $mutatingScope);
return;
}

if ($node instanceof NullableType) {
$node->type->setAttribute(AttributeKey::SCOPE, $mutatingScope);
return;
Expand Down