Skip to content

Commit

Permalink
FileProvider should never be access by rule
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Jun 26, 2024
1 parent b1ee7a6 commit 3fc330a
Showing 1 changed file with 10 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use Rector\Provider\CurrentFileProvider;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\Application\File;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

Expand All @@ -25,13 +23,16 @@ final class DowngradeNullsafeToTernaryOperatorRector extends AbstractRector
{
private int $counter = 0;

private ?string $previousFileName = null;

private ?string $currentFileName = null;

public function __construct(
private readonly CurrentFileProvider $currentFileProvider
) {
/**
* Hack-ish way to reset counter for a new file, to avoid rising counter for each file
*
* @param \PhpParser\Node[] $nodes
* @return array|Node[]|null
*/
public function beforeTraverse(array $nodes): ?array
{
$this->counter = 0;
return parent::beforeTraverse($nodes);
}

public function getRuleDefinition(): RuleDefinition
Expand Down Expand Up @@ -62,22 +63,6 @@ public function getNodeTypes(): array
*/
public function refactor(Node $node): ?Ternary
{
if ($this->previousFileName === null) {
$previousFile = $this->currentFileProvider->getFile();
if (! $previousFile instanceof File) {
return null;
}

$this->previousFileName = $previousFile->getFilePath();
}

$currentFile = $this->currentFileProvider->getFile();
if (! $currentFile instanceof File) {
return null;
}

$this->currentFileName = $currentFile->getFilePath();

$nullsafeVariable = $this->createNullsafeVariable();

$methodCallOrPropertyFetch = $node instanceof NullsafeMethodCall
Expand All @@ -91,13 +76,7 @@ public function refactor(Node $node): ?Ternary

private function createNullsafeVariable(): Variable
{
if ($this->previousFileName !== $this->currentFileName) {
$this->counter = 0;
$this->previousFileName = $this->currentFileName;
}

$nullsafeVariableName = 'nullsafeVariable' . ++$this->counter;

return new Variable($nullsafeVariableName);
}
}

0 comments on commit 3fc330a

Please sign in to comment.