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

CurrentFileProvider should never be access by rule #226

Merged
merged 2 commits into from
Jun 26, 2024
Merged
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
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 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);
}
}