From b38342508ed182f9a5edbbc0b2d91590c901e6d6 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Sun, 25 May 2025 23:26:35 +0200 Subject: [PATCH] Add numeric check on unary plus and unary minus --- README.md | 44 ++++++++--------- rules.neon | 10 ++++ .../OperandInArithmeticUnaryMinusRule.php | 47 +++++++++++++++++++ .../OperandInArithmeticUnaryPlusRule.php | 47 +++++++++++++++++++ .../OperandInArithmeticUnaryMinusRuleTest.php | 34 ++++++++++++++ .../OperandInArithmeticUnaryPlusRuleTest.php | 34 ++++++++++++++ tests/Rules/Operators/data/operators.php | 16 +++++++ 7 files changed, 210 insertions(+), 22 deletions(-) create mode 100644 src/Rules/Operators/OperandInArithmeticUnaryMinusRule.php create mode 100644 src/Rules/Operators/OperandInArithmeticUnaryPlusRule.php create mode 100644 tests/Rules/Operators/OperandInArithmeticUnaryMinusRuleTest.php create mode 100644 tests/Rules/Operators/OperandInArithmeticUnaryPlusRuleTest.php diff --git a/README.md b/README.md index 85b9a5ab..51e4997e 100644 --- a/README.md +++ b/README.md @@ -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`:
* `in_array` (3rd parameter)
* `array_search` (3rd parameter)
* `array_keys` (3rd parameter; only if the 2nd parameter `$search_value` is provided)
* `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! diff --git a/rules.neon b/rules.neon index dd20b8d1..0219f1ff 100644 --- a/rules.neon +++ b/rules.neon @@ -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: @@ -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 diff --git a/src/Rules/Operators/OperandInArithmeticUnaryMinusRule.php b/src/Rules/Operators/OperandInArithmeticUnaryMinusRule.php new file mode 100644 index 00000000..d3db7df5 --- /dev/null +++ b/src/Rules/Operators/OperandInArithmeticUnaryMinusRule.php @@ -0,0 +1,47 @@ + + */ +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; + } + +} diff --git a/src/Rules/Operators/OperandInArithmeticUnaryPlusRule.php b/src/Rules/Operators/OperandInArithmeticUnaryPlusRule.php new file mode 100644 index 00000000..78313d8c --- /dev/null +++ b/src/Rules/Operators/OperandInArithmeticUnaryPlusRule.php @@ -0,0 +1,47 @@ + + */ +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; + } + +} diff --git a/tests/Rules/Operators/OperandInArithmeticUnaryMinusRuleTest.php b/tests/Rules/Operators/OperandInArithmeticUnaryMinusRuleTest.php new file mode 100644 index 00000000..d202bdbc --- /dev/null +++ b/tests/Rules/Operators/OperandInArithmeticUnaryMinusRuleTest.php @@ -0,0 +1,34 @@ + + */ +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, + ], + ]); + } + +} diff --git a/tests/Rules/Operators/OperandInArithmeticUnaryPlusRuleTest.php b/tests/Rules/Operators/OperandInArithmeticUnaryPlusRuleTest.php new file mode 100644 index 00000000..6cc253a3 --- /dev/null +++ b/tests/Rules/Operators/OperandInArithmeticUnaryPlusRuleTest.php @@ -0,0 +1,34 @@ + + */ +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, + ], + ]); + } + +} diff --git a/tests/Rules/Operators/data/operators.php b/tests/Rules/Operators/data/operators.php index f3e75598..0c230064 100644 --- a/tests/Rules/Operators/data/operators.php +++ b/tests/Rules/Operators/data/operators.php @@ -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;