Skip to content

Commit c0d321f

Browse files
Add numeric check on unary plus and unary minus
1 parent 73c5baa commit c0d321f

File tree

7 files changed

+215
-22
lines changed

7 files changed

+215
-22
lines changed

README.md

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,29 +6,29 @@
66

77
[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:
88

9-
| Configuration Parameters | Rule Description |
10-
|:---------------------------------------|:--------------------------------------------------------------------------------------------------------|
11-
| `booleansInConditions` | Require booleans in `if`, `elseif`, ternary operator, after `!`, and on both sides of `&&` and `\|\|`. |
12-
| `booleansInLoopConditions` | Require booleans in `while` and `do while` loop conditions. |
13-
| `numericOperandsInArithmeticOperators` | Require numeric operands or arrays in `+` and numeric operands in `-`/`*`/`/`/`**`/`%`. |
14-
| `numericOperandsInArithmeticOperators` | Require numeric operand in `$var++`, `$var--`, `++$var`and `--$var`. |
9+
| Configuration Parameters | Rule Description |
10+
|:---------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
11+
| `booleansInConditions` | Require booleans in `if`, `elseif`, ternary operator, after `!`, and on both sides of `&&` and `\|\|`. |
12+
| `booleansInLoopConditions` | Require booleans in `while` and `do while` loop conditions. |
13+
| `numericOperandsInArithmeticOperators` | Require numeric operands or arrays in `+` and numeric operands in `-`/`*`/`/`/`**`/`%`. |
14+
| `numericOperandsInArithmeticOperators` | Require numeric operand in `+$var`, `-$var`, `$var++`, `$var--`, `++$var` and `--$var`. |
1515
| `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). |
16-
| `overwriteVariablesWithLoop` | Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop. |
17-
| `overwriteVariablesWithLoop` | Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop. |
18-
| `switchConditionsMatchingType` | Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results. |
19-
| `dynamicCallOnStaticMethod` | Check that statically declared methods are called statically. |
20-
| `disallowedEmpty` | Disallow `empty()` - it's a very loose comparison (see [manual](https://php.net/empty)), it's recommended to use more strict one. |
21-
| `disallowedShortTernary` | Disallow short ternary operator (`?:`) - implies weak comparison, it's recommended to use null coalesce operator (`??`) or ternary operator with strict condition. |
22-
| `noVariableVariables` | Disallow variable variables (`$$foo`, `$this->$method()` etc.). |
23-
| `overwriteVariablesWithLoop` | Disallow overwriting variables with foreach key and value variables. |
24-
| `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. |
25-
| | Correct case for referenced and called function names. |
26-
| `matchingInheritedMethodNames` | Correct case for inherited and implemented method names. |
27-
| | Contravariance for parameter types and covariance for return types in inherited methods (also known as Liskov substitution principle - LSP).|
28-
| | Check LSP even for static methods. |
29-
| `requireParentConstructorCall` | Require calling parent constructor. |
30-
| `disallowedBacktick` | Disallow usage of backtick operator (`` $ls = `ls -la` ``). |
31-
| `closureUsesThis` | Closure should use `$this` directly instead of using `$this` variable indirectly. |
16+
| `overwriteVariablesWithLoop` | Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop. |
17+
| `overwriteVariablesWithLoop` | Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop. |
18+
| `switchConditionsMatchingType` | Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results. |
19+
| `dynamicCallOnStaticMethod` | Check that statically declared methods are called statically. |
20+
| `disallowedEmpty` | Disallow `empty()` - it's a very loose comparison (see [manual](https://php.net/empty)), it's recommended to use more strict one. |
21+
| `disallowedShortTernary` | Disallow short ternary operator (`?:`) - implies weak comparison, it's recommended to use null coalesce operator (`??`) or ternary operator with strict condition. |
22+
| `noVariableVariables` | Disallow variable variables (`$$foo`, `$this->$method()` etc.). |
23+
| `overwriteVariablesWithLoop` | Disallow overwriting variables with foreach key and value variables. |
24+
| `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. |
25+
| | Correct case for referenced and called function names. |
26+
| `matchingInheritedMethodNames` | Correct case for inherited and implemented method names. |
27+
| | Contravariance for parameter types and covariance for return types in inherited methods (also known as Liskov substitution principle - LSP). |
28+
| | Check LSP even for static methods. |
29+
| `requireParentConstructorCall` | Require calling parent constructor. |
30+
| `disallowedBacktick` | Disallow usage of backtick operator (`` $ls = `ls -la` ``). |
31+
| `closureUsesThis` | Closure should use `$this` directly instead of using `$this` variable indirectly. |
3232

3333
Additional rules are coming in subsequent releases!
3434

rules.neon

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ conditionalTags:
106106
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
107107
PHPStan\Rules\Operators\OperandInArithmeticPreIncrementRule:
108108
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
109+
PHPStan\Rules\Operators\OperandInArithmeticUnaryMinusRule:
110+
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
111+
PHPStan\Rules\Operators\OperandInArithmeticUnaryPlusRule:
112+
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
109113
PHPStan\Rules\Operators\OperandsInArithmeticAdditionRule:
110114
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
111115
PHPStan\Rules\Operators\OperandsInArithmeticDivisionRule:
@@ -242,6 +246,12 @@ services:
242246
-
243247
class: PHPStan\Rules\Operators\OperandInArithmeticPreIncrementRule
244248

249+
-
250+
class: PHPStan\Rules\Operators\OperandInArithmeticUnaryMinusRule
251+
252+
-
253+
class: PHPStan\Rules\Operators\OperandInArithmeticUnaryPlusRule
254+
245255
-
246256
class: PHPStan\Rules\Operators\OperandsInArithmeticAdditionRule
247257

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Operators;
4+
5+
use PhpParser\Node;
6+
use PhpParser\Node\Expr\UnaryMinus;
7+
use PHPStan\Analyser\Scope;
8+
use PHPStan\Rules\Rule;
9+
use PHPStan\Rules\RuleErrorBuilder;
10+
use PHPStan\Type\VerbosityLevel;
11+
12+
/**
13+
* @phpstan-extends Rule<UnaryMinus>
14+
*/
15+
class OperandInArithmeticUnaryMinusRule implements Rule
16+
{
17+
18+
private OperatorRuleHelper $helper;
19+
20+
public function __construct(OperatorRuleHelper $helper)
21+
{
22+
$this->helper = $helper;
23+
}
24+
25+
public function getNodeType(): string
26+
{
27+
return UnaryMinus::class;
28+
}
29+
30+
public function processNode(Node $node, Scope $scope): array
31+
{
32+
$messages = [];
33+
34+
if (!$this->helper->isValidForArithmeticOperation($scope, $node->expr)) {
35+
$varType = $scope->getType($node->expr);
36+
37+
$messages[] = RuleErrorBuilder::message(sprintf(
38+
'Only numeric types are allowed in unary -, %s given.',
39+
$varType->describe(VerbosityLevel::typeOnly()),
40+
))->identifier('unaryMinus.nonNumeric')->build();
41+
}
42+
43+
return $messages;
44+
}
45+
46+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Operators;
4+
5+
use PhpParser\Node;
6+
use PhpParser\Node\Expr\UnaryPlus;
7+
use PHPStan\Analyser\Scope;
8+
use PHPStan\Rules\Rule;
9+
use PHPStan\Rules\RuleErrorBuilder;
10+
use PHPStan\Type\VerbosityLevel;
11+
12+
/**
13+
* @phpstan-extends Rule<UnaryPlus>
14+
*/
15+
class OperandInArithmeticUnaryPlusRule implements Rule
16+
{
17+
18+
private OperatorRuleHelper $helper;
19+
20+
public function __construct(OperatorRuleHelper $helper)
21+
{
22+
$this->helper = $helper;
23+
}
24+
25+
public function getNodeType(): string
26+
{
27+
return UnaryPlus::class;
28+
}
29+
30+
public function processNode(Node $node, Scope $scope): array
31+
{
32+
$messages = [];
33+
34+
if (!$this->helper->isValidForArithmeticOperation($scope, $node->expr)) {
35+
$varType = $scope->getType($node->expr);
36+
37+
$messages[] = RuleErrorBuilder::message(sprintf(
38+
'Only numeric types are allowed in unary +, %s given.',
39+
$varType->describe(VerbosityLevel::typeOnly()),
40+
))->identifier('unaryPlus.nonNumeric')->build();
41+
}
42+
43+
return $messages;
44+
}
45+
46+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Rules\Operators;
4+
5+
use PHPStan\Rules\Operators\OperandInArithmeticUnaryMinusRule;
6+
use PHPStan\Rules\Operators\OperandsInArithmeticSubtractionRule;
7+
use PHPStan\Rules\Operators\OperatorRuleHelper;
8+
use PHPStan\Rules\Rule;
9+
use PHPStan\Rules\RuleLevelHelper;
10+
use PHPStan\Testing\RuleTestCase;
11+
12+
/**
13+
* @extends RuleTestCase<OperandInArithmeticUnaryMinusRule>
14+
*/
15+
class OperandInArithmeticUnaryMinusRuleTest extends RuleTestCase
16+
{
17+
18+
protected function getRule(): Rule
19+
{
20+
return new OperandInArithmeticUnaryMinusRule(
21+
new OperatorRuleHelper(
22+
self::getContainer()->getByType(RuleLevelHelper::class),
23+
),
24+
);
25+
}
26+
27+
public function testRule(): void
28+
{
29+
$this->analyse([__DIR__ . '/data/operators.php'], [
30+
[
31+
'Only numeric types are allowed in unary -, null given.',
32+
233,
33+
],
34+
]);
35+
}
36+
37+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Rules\Operators;
4+
5+
use PHPStan\Rules\Operators\OperandInArithmeticUnaryMinusRule;
6+
use PHPStan\Rules\Operators\OperandInArithmeticUnaryPlusRule;
7+
use PHPStan\Rules\Operators\OperandsInArithmeticSubtractionRule;
8+
use PHPStan\Rules\Operators\OperatorRuleHelper;
9+
use PHPStan\Rules\Rule;
10+
use PHPStan\Rules\RuleLevelHelper;
11+
use PHPStan\Testing\RuleTestCase;
12+
13+
/**
14+
* @extends RuleTestCase<OperandInArithmeticUnaryPlusRule>
15+
*/
16+
class OperandInArithmeticUnaryPlusRuleTest extends RuleTestCase
17+
{
18+
19+
protected function getRule(): Rule
20+
{
21+
return new OperandInArithmeticUnaryPlusRule(
22+
new OperatorRuleHelper(
23+
self::getContainer()->getByType(RuleLevelHelper::class),
24+
),
25+
);
26+
}
27+
28+
public function testRule(): void
29+
{
30+
$this->analyse([__DIR__ . '/data/operators.php'], [
31+
[
32+
'Only numeric types are allowed in unary +, null given.',
33+
225,
34+
],
35+
]);
36+
}
37+
38+
}

tests/Rules/Operators/data/operators.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,19 @@ function (array $array, int $int, $mixed) {
215215
/** @var numeric-string $numericString */
216216
$numericString = doFoo();
217217
$numericString += 1;
218+
219+
+$int;
220+
+$float;
221+
+$intOrFloat;
222+
+$string;
223+
+$array;
224+
+$object;
225+
+$null;
226+
227+
-$int;
228+
-$float;
229+
-$intOrFloat;
230+
-$string;
231+
-$array;
232+
-$object;
233+
-$null;

0 commit comments

Comments
 (0)