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

[DowngradePhp73] Skip inside define check on DowngradePhp73JsonConstRector #1787

Merged
merged 2 commits into from
Feb 8, 2022
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\DowngradePhp73\Rector\FuncCall\DowngradePhp73JsonConstRector\Fixture;

class SkipInsideDefineCheck
{
public function run($options)
{
if (\defined('JSON_THROW_ON_ERROR')) {
$options = $options & ~\JSON_THROW_ON_ERROR;
}
}
}
35 changes: 34 additions & 1 deletion rules/DowngradePhp72/NodeManipulator/JsonConstCleaner.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,22 @@

namespace Rector\DowngradePhp72\NodeManipulator;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\BitwiseOr;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;

final class JsonConstCleaner
{
public function __construct(
private readonly NodeNameResolver $nodeNameResolver
private readonly NodeNameResolver $nodeNameResolver,
private readonly BetterNodeFinder $betterNodeFinder
) {
}

Expand All @@ -23,6 +28,34 @@ public function __construct(
*/
public function clean(ConstFetch|BitwiseOr $node, array $constants): ConstFetch|Expr|null
{
$defined = (bool) $this->betterNodeFinder->findFirstPreviousOfNode(
$node,
function (Node $subNode) use ($constants): bool {
if (! $subNode instanceof FuncCall) {
return false;
}

if (! $this->nodeNameResolver->isName($subNode, 'defined')) {
return false;
}

$args = $subNode->getArgs();
if (! isset($args[0])) {
return false;
}

if (! $args[0]->value instanceof String_) {
return false;
}

return in_array($args[0]->value->value, $constants, true);
}
);

if ($defined) {
return null;
}

if ($node instanceof ConstFetch) {
return $this->cleanByConstFetch($node, $constants);
}
Expand Down