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

Detect variable reuse with different type #111

Open
szepeviktor opened this issue Jun 28, 2020 · 6 comments
Open

Detect variable reuse with different type #111

szepeviktor opened this issue Jun 28, 2020 · 6 comments

Comments

@szepeviktor
Copy link

Feature request

I think this is okay.

$var = 'apple';
$var = 'nice ' . $var;

But many developers tend to stuff other type into the same variable.

$list = [1, 2, 3];
$list = \implode(', ', $list);

Could PHPStan warn me when a variable's type changes?

@szepeviktor
Copy link
Author

Even this.

$list = [1, 2, 3];
$list = 'apple';

@ondrejmirtes
Copy link
Member

It's really easy to implement your custom rule that checks this, but it's hard to not be too annoying, for example in cases like these:

$test = null;
if (rand(0, 1)) {
    $test = new Foo();
}

@szepeviktor
Copy link
Author

implement your custom rule

Okay :) so it is up to me?

Could you start me up with 2 sentences?

@szepeviktor
Copy link
Author

/** @var Foo|null $test */
$test = null;
if (rand(0, 1)) {
    $test = new Foo();
}

@ondrejmirtes
Copy link
Member

  1. https://phpstan.org/developing-extensions/rules
  2. getNodeType should return Assign::class
  3. in processNode you should check that on the left side (var property of $node) there's Variable node. If not, return [].
  4. Ask scope about $scope->hasVariableType. If it's not yes(), return []
  5. Get current type of the variable from scope, and compare it with $scope->getType($node->expr). You can use Type::equals() or Type::isSuperTypeOf, depends on your requirements.
  6. Return message if the types are different enough.

@szepeviktor
Copy link
Author

Thank you.

@ondrejmirtes ondrejmirtes transferred this issue from phpstan/phpstan Jun 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants