Skip to content

Add numeric check on unary plus and unary minus #273

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

Open
wants to merge 1 commit into
base: 2.0.x
Choose a base branch
from
Open
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
44 changes: 22 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,29 @@

[PHPStan](https://phpstan.org/) focuses on finding bugs in your code. But in PHP there's a lot of leeway in how stuff can be written. This repository contains additional rules that revolve around strictly and strongly typed code with no loose casting for those who want additional safety in extremely defensive programming:

| Configuration Parameters | Rule Description |
|:---------------------------------------|:--------------------------------------------------------------------------------------------------------|
| `booleansInConditions` | Require booleans in `if`, `elseif`, ternary operator, after `!`, and on both sides of `&&` and `\|\|`. |
| `booleansInLoopConditions` | Require booleans in `while` and `do while` loop conditions. |
| `numericOperandsInArithmeticOperators` | Require numeric operands or arrays in `+` and numeric operands in `-`/`*`/`/`/`**`/`%`. |
| `numericOperandsInArithmeticOperators` | Require numeric operand in `$var++`, `$var--`, `++$var`and `--$var`. |
| Configuration Parameters | Rule Description |
|:---------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `booleansInConditions` | Require booleans in `if`, `elseif`, ternary operator, after `!`, and on both sides of `&&` and `\|\|`. |
| `booleansInLoopConditions` | Require booleans in `while` and `do while` loop conditions. |
| `numericOperandsInArithmeticOperators` | Require numeric operands or arrays in `+` and numeric operands in `-`/`*`/`/`/`**`/`%`. |
| `numericOperandsInArithmeticOperators` | Require numeric operand in `+$var`, `-$var`, `$var++`, `$var--`, `++$var` and `--$var`. |
| `strictFunctionCalls` | These functions contain a `$strict` parameter for better type safety, it must be set to `true`:<br>* `in_array` (3rd parameter)<br>* `array_search` (3rd parameter)<br>* `array_keys` (3rd parameter; only if the 2nd parameter `$search_value` is provided)<br>* `base64_decode` (2nd parameter). |
| `overwriteVariablesWithLoop` | Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop. |
| `overwriteVariablesWithLoop` | Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop. |
| `switchConditionsMatchingType` | Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results. |
| `dynamicCallOnStaticMethod` | Check that statically declared methods are called statically. |
| `disallowedEmpty` | Disallow `empty()` - it's a very loose comparison (see [manual](https://php.net/empty)), it's recommended to use more strict one. |
| `disallowedShortTernary` | Disallow short ternary operator (`?:`) - implies weak comparison, it's recommended to use null coalesce operator (`??`) or ternary operator with strict condition. |
| `noVariableVariables` | Disallow variable variables (`$$foo`, `$this->$method()` etc.). |
| `overwriteVariablesWithLoop` | Disallow overwriting variables with foreach key and value variables. |
| `checkAlwaysTrueInstanceof`, `checkAlwaysTrueCheckTypeFunctionCall`, `checkAlwaysTrueStrictComparison` | Always true `instanceof`, type-checking `is_*` functions and strict comparisons `===`/`!==`. These checks can be turned off by setting `checkAlwaysTrueInstanceof`, `checkAlwaysTrueCheckTypeFunctionCall` and `checkAlwaysTrueStrictComparison` to false. |
| | Correct case for referenced and called function names. |
| `matchingInheritedMethodNames` | Correct case for inherited and implemented method names. |
| | Contravariance for parameter types and covariance for return types in inherited methods (also known as Liskov substitution principle - LSP).|
| | Check LSP even for static methods. |
| `requireParentConstructorCall` | Require calling parent constructor. |
| `disallowedBacktick` | Disallow usage of backtick operator (`` $ls = `ls -la` ``). |
| `closureUsesThis` | Closure should use `$this` directly instead of using `$this` variable indirectly. |
| `overwriteVariablesWithLoop` | Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop. |
| `overwriteVariablesWithLoop` | Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop. |
| `switchConditionsMatchingType` | Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results. |
| `dynamicCallOnStaticMethod` | Check that statically declared methods are called statically. |
| `disallowedEmpty` | Disallow `empty()` - it's a very loose comparison (see [manual](https://php.net/empty)), it's recommended to use more strict one. |
| `disallowedShortTernary` | Disallow short ternary operator (`?:`) - implies weak comparison, it's recommended to use null coalesce operator (`??`) or ternary operator with strict condition. |
| `noVariableVariables` | Disallow variable variables (`$$foo`, `$this->$method()` etc.). |
| `overwriteVariablesWithLoop` | Disallow overwriting variables with foreach key and value variables. |
| `checkAlwaysTrueInstanceof`, `checkAlwaysTrueCheckTypeFunctionCall`, `checkAlwaysTrueStrictComparison` | Always true `instanceof`, type-checking `is_*` functions and strict comparisons `===`/`!==`. These checks can be turned off by setting `checkAlwaysTrueInstanceof`, `checkAlwaysTrueCheckTypeFunctionCall` and `checkAlwaysTrueStrictComparison` to false. |
| | Correct case for referenced and called function names. |
| `matchingInheritedMethodNames` | Correct case for inherited and implemented method names. |
| | Contravariance for parameter types and covariance for return types in inherited methods (also known as Liskov substitution principle - LSP). |
| | Check LSP even for static methods. |
| `requireParentConstructorCall` | Require calling parent constructor. |
| `disallowedBacktick` | Disallow usage of backtick operator (`` $ls = `ls -la` ``). |
| `closureUsesThis` | Closure should use `$this` directly instead of using `$this` variable indirectly. |

Additional rules are coming in subsequent releases!

Expand Down
10 changes: 10 additions & 0 deletions rules.neon
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ conditionalTags:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandInArithmeticPreIncrementRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandInArithmeticUnaryMinusRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandInArithmeticUnaryPlusRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticAdditionRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticDivisionRule:
Expand Down Expand Up @@ -242,6 +246,12 @@ services:
-
class: PHPStan\Rules\Operators\OperandInArithmeticPreIncrementRule

-
class: PHPStan\Rules\Operators\OperandInArithmeticUnaryMinusRule

-
class: PHPStan\Rules\Operators\OperandInArithmeticUnaryPlusRule

-
class: PHPStan\Rules\Operators\OperandsInArithmeticAdditionRule

Expand Down
47 changes: 47 additions & 0 deletions src/Rules/Operators/OperandInArithmeticUnaryMinusRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Operators;

use PhpParser\Node;
use PhpParser\Node\Expr\UnaryMinus;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\VerbosityLevel;
use function sprintf;

/**
* @phpstan-implements Rule<UnaryMinus>
*/
class OperandInArithmeticUnaryMinusRule implements Rule
{

private OperatorRuleHelper $helper;

public function __construct(OperatorRuleHelper $helper)
{
$this->helper = $helper;
}

public function getNodeType(): string
{
return UnaryMinus::class;
}

public function processNode(Node $node, Scope $scope): array
{
$messages = [];

if (!$this->helper->isValidForArithmeticOperation($scope, $node->expr)) {
$varType = $scope->getType($node->expr);

$messages[] = RuleErrorBuilder::message(sprintf(
'Only numeric types are allowed in unary -, %s given.',
$varType->describe(VerbosityLevel::typeOnly()),
))->identifier('unaryMinus.nonNumeric')->build();
}

return $messages;
}

}
47 changes: 47 additions & 0 deletions src/Rules/Operators/OperandInArithmeticUnaryPlusRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Operators;

use PhpParser\Node;
use PhpParser\Node\Expr\UnaryPlus;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\VerbosityLevel;
use function sprintf;

/**
* @phpstan-implements Rule<UnaryPlus>
*/
class OperandInArithmeticUnaryPlusRule implements Rule
{

private OperatorRuleHelper $helper;

public function __construct(OperatorRuleHelper $helper)
{
$this->helper = $helper;
}

public function getNodeType(): string
{
return UnaryPlus::class;
}

public function processNode(Node $node, Scope $scope): array
{
$messages = [];

if (!$this->helper->isValidForArithmeticOperation($scope, $node->expr)) {
$varType = $scope->getType($node->expr);

$messages[] = RuleErrorBuilder::message(sprintf(
'Only numeric types are allowed in unary +, %s given.',
$varType->describe(VerbosityLevel::typeOnly()),
))->identifier('unaryPlus.nonNumeric')->build();
}

return $messages;
}

}
34 changes: 34 additions & 0 deletions tests/Rules/Operators/OperandInArithmeticUnaryMinusRuleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Operators;

use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Testing\RuleTestCase;

/**
* @extends RuleTestCase<OperandInArithmeticUnaryMinusRule>
*/
class OperandInArithmeticUnaryMinusRuleTest extends RuleTestCase
{

protected function getRule(): Rule
{
return new OperandInArithmeticUnaryMinusRule(
new OperatorRuleHelper(
self::getContainer()->getByType(RuleLevelHelper::class),
),
);
}

public function testRule(): void
{
$this->analyse([__DIR__ . '/data/operators.php'], [
[
'Only numeric types are allowed in unary -, null given.',
233,
],
]);
}

}
34 changes: 34 additions & 0 deletions tests/Rules/Operators/OperandInArithmeticUnaryPlusRuleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Operators;

use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Testing\RuleTestCase;

/**
* @extends RuleTestCase<OperandInArithmeticUnaryPlusRule>
*/
class OperandInArithmeticUnaryPlusRuleTest extends RuleTestCase
{

protected function getRule(): Rule
{
return new OperandInArithmeticUnaryPlusRule(
new OperatorRuleHelper(
self::getContainer()->getByType(RuleLevelHelper::class),
),
);
}

public function testRule(): void
{
$this->analyse([__DIR__ . '/data/operators.php'], [
[
'Only numeric types are allowed in unary +, null given.',
225,
],
]);
}

}
16 changes: 16 additions & 0 deletions tests/Rules/Operators/data/operators.php
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,19 @@ function (array $array, int $int, $mixed) {
/** @var numeric-string $numericString */
$numericString = doFoo();
$numericString += 1;

+$int;
+$float;
+$intOrFloat;
+$string;
+$array;
+$object;
+$null;

-$int;
-$float;
-$intOrFloat;
-$string;
-$array;
-$object;
-$null;