Skip to content

Commit

Permalink
[DowngradePhp73] Skip inside define check on DowngradePhp73JsonConstR…
Browse files Browse the repository at this point in the history
…ector (#1787)

* [DowngradePhp73] Skip inside define check on DowngradePhp73JsonConstRector

* Fixed 🎉
  • Loading branch information
samsonasik authored Feb 8, 2022
1 parent f03e2a1 commit cd7140a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
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

0 comments on commit cd7140a

Please sign in to comment.