From 04f299fb0ee7eed4a8e70ab60e6205d9ccd1f3e4 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 24 Mar 2025 03:31:34 +0000 Subject: [PATCH 1/6] Update metcalfc/changelog-generator action to v4.5.0 --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b1a669a..be6cad0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,7 @@ jobs: - name: Generate changelog id: changelog - uses: metcalfc/changelog-generator@v4.3.1 + uses: metcalfc/changelog-generator@v4.5.0 with: myToken: ${{ secrets.PHPSTAN_BOT_TOKEN }} From 3ecc310efdb91a25415b7eca9234b6525cdfcc0c Mon Sep 17 00:00:00 2001 From: simon-tma Date: Mon, 24 Mar 2025 07:12:15 +1100 Subject: [PATCH 2/6] Use relative links for rules.neon The changes to default parameters are different in different branches, so we want to link to the current branch's version of `rules.neon`. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 88b7e96..35e3a07 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ parameters: illegalConstructorMethodCall: false ``` -Aside from introducing new custom rules, phpstan-strict-rules also [change the default values of some configuration parameters](https://github.com/phpstan/phpstan-strict-rules/blob/1.6.x/rules.neon#L1) that are present in PHPStan itself. These parameters are [documented on phpstan.org](https://phpstan.org/config-reference#stricter-analysis). +Aside from introducing new custom rules, phpstan-strict-rules also [change the default values of some configuration parameters](./rules.neon#L1) that are present in PHPStan itself. These parameters are [documented on phpstan.org](https://phpstan.org/config-reference#stricter-analysis). ## Enabling rules one-by-one @@ -107,4 +107,4 @@ parameters: booleansInConditions: true ``` -Even with `strictRules.allRules` set to `false`, part of this package is still in effect. That's because phpstan-strict-rules also [change the default values of some configuration parameters](https://github.com/phpstan/phpstan-strict-rules/blob/1.6.x/rules.neon#L1) that are present in PHPStan itself. These parameters are [documented on phpstan.org](https://phpstan.org/config-reference#stricter-analysis). +Even with `strictRules.allRules` set to `false`, part of this package is still in effect. That's because phpstan-strict-rules also [change the default values of some configuration parameters](./rules.neon#L1) that are present in PHPStan itself. These parameters are [documented on phpstan.org](https://phpstan.org/config-reference#stricter-analysis). From f203fecee620934db200857729453d1180270823 Mon Sep 17 00:00:00 2001 From: Osita Ugwueze <54801980+OsitaDNU@users.noreply.github.com> Date: Sun, 30 Mar 2025 10:12:07 +0100 Subject: [PATCH 3/6] Match Rule Descriptions with Configuration Parameters in README.md --- README.md | 48 +++++++++++++++++++++++------------------------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 35e3a07..85b9a5a 100644 --- a/README.md +++ b/README.md @@ -6,31 +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: -* Require booleans in `if`, `elseif`, ternary operator, after `!`, and on both sides of `&&` and `||`. -* Require booleans in `while` and `do while` loop conditions. -* Require numeric operands or arrays in `+` and numeric operands in `-`/`*`/`/`/`**`/`%`. -* Require numeric operand in `$var++`, `$var--`, `++$var`and `--$var`. -* 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) -* Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop. -* Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop. -* Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results. -* Check that statically declared methods are called statically. -* Disallow `empty()` - it's a very loose comparison (see [manual](https://php.net/empty)), it's recommended to use more strict one. -* Disallow short ternary operator (`?:`) - implies weak comparison, it's recommended to use null coalesce operator (`??`) or ternary operator with strict condition. -* Disallow variable variables (`$$foo`, `$this->$method()` etc.) -* Disallow overwriting variables with foreach key and value variables -* Always true `instanceof`, type-checking `is_*` functions and strict comparisons `===`/`!==`. These checks can be turned off by setting `checkAlwaysTrueInstanceof`/`checkAlwaysTrueCheckTypeFunctionCall`/`checkAlwaysTrueStrictComparison` to false. -* Correct case for referenced and called function names. -* 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 -* Require calling parent constructor -* Disallow usage of backtick operator (`` $ls = `ls -la` ``) -* Closure should use `$this` directly instead of using `$this` variable indirectly +| 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`. | +| `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. | Additional rules are coming in subsequent releases! From 73c5baac769505ed05fc0e709ad102e6c6698edf Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 7 Apr 2025 03:22:50 +0000 Subject: [PATCH 4/6] Update metcalfc/changelog-generator action to v4.6.2 --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index be6cad0..b8c96d4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,7 @@ jobs: - name: Generate changelog id: changelog - uses: metcalfc/changelog-generator@v4.5.0 + uses: metcalfc/changelog-generator@v4.6.2 with: myToken: ${{ secrets.PHPSTAN_BOT_TOKEN }} From 1f1358da2f8e1317478c63c21beb9918c9821f6f Mon Sep 17 00:00:00 2001 From: Markus Staab Date: Sun, 8 Jun 2025 11:25:52 +0200 Subject: [PATCH 5/6] UselessCastRule: do cheaper check first --- src/Rules/Cast/UselessCastRule.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Rules/Cast/UselessCastRule.php b/src/Rules/Cast/UselessCastRule.php index ca8f226..6629750 100644 --- a/src/Rules/Cast/UselessCastRule.php +++ b/src/Rules/Cast/UselessCastRule.php @@ -55,12 +55,12 @@ public function processNode(Node $node, Scope $scope): array return $ruleErrorBuilder; } - $expressionTypeWithoutPhpDoc = $scope->getNativeType($node->expr); - if ($castType->isSuperTypeOf($expressionTypeWithoutPhpDoc)->yes()) { + if (!$this->treatPhpDocTypesAsCertainTip) { return $ruleErrorBuilder; } - if (!$this->treatPhpDocTypesAsCertainTip) { + $expressionTypeWithoutPhpDoc = $scope->getNativeType($node->expr); + if ($castType->isSuperTypeOf($expressionTypeWithoutPhpDoc)->yes()) { return $ruleErrorBuilder; } From f9f77efa9de31992a832ff77ea52eb42d675b094 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Fri, 18 Jul 2025 23:11:36 +0200 Subject: [PATCH 6/6] Add numeric check on unary plus and unary minus --- README.md | 2 +- 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, 189 insertions(+), 1 deletion(-) 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 85b9a5a..e56aa34 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ |:---------------------------------------|:--------------------------------------------------------------------------------------------------------| | `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`. | | `numericOperandsInArithmeticOperators` | Require numeric operand in `$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. | diff --git a/rules.neon b/rules.neon index dd20b8d..7a63c4e 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%, %featureToggles.bleedingEdge%] + PHPStan\Rules\Operators\OperandInArithmeticUnaryPlusRule: + phpstan.rules.rule: [%strictRules.numericOperandsInArithmeticOperators%, %featureToggles.bleedingEdge%] 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 0000000..d3db7df --- /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 0000000..78313d8 --- /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 0000000..d202bdb --- /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 0000000..6cc253a --- /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 f3e7559..0c23006 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;