Skip to content

Commit f06d0ca

Browse files
committed
Disallow empty()
1 parent 8d121df commit f06d0ca

File tree

5 files changed

+60
-0
lines changed

5 files changed

+60
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop.
1616
* Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results.
1717
* Statically declared methods are called statically.
18+
* Disallow `empty()` - it's a very loose comparison (see [manual)(https://secure.php.net/manual/en/function.empty.php)), it's recommended to use more strict one.
1819

1920
Additional rules are coming in subsequent releases!
2021

Diff for: rules.neon

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ rules:
88
- PHPStan\Rules\BooleansInConditions\BooleanInElseIfConditionRule
99
- PHPStan\Rules\BooleansInConditions\BooleanInIfConditionRule
1010
- PHPStan\Rules\BooleansInConditions\BooleanInTernaryOperatorRule
11+
- PHPStan\Rules\DisallowedConstructs\DisallowedEmptyRule
1112
- PHPStan\Rules\StrictCalls\DynamicCallOnStaticMethodsRule
1213
- PHPStan\Rules\StrictCalls\StrictFunctionCallsRule
1314
- PHPStan\Rules\SwitchConditions\MatchingTypeInSwitchCaseConditionRule
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\DisallowedConstructs;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
8+
class DisallowedEmptyRule implements \PHPStan\Rules\Rule
9+
{
10+
11+
public function getNodeType(): string
12+
{
13+
return \PhpParser\Node\Expr\Empty_::class;
14+
}
15+
16+
/**
17+
* @param \PhpParser\Node\Expr\Empty_ $node
18+
* @param \PHPStan\Analyser\Scope $scope
19+
* @return string[]
20+
*/
21+
public function processNode(Node $node, Scope $scope): array
22+
{
23+
return [
24+
'Construct empty() is not allowed. Use more strict comparison.',
25+
];
26+
}
27+
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\DisallowedConstructs;
4+
5+
use PHPStan\Rules\Rule;
6+
7+
class DisallowedEmptyRuleTest extends \PHPStan\Testing\RuleTestCase
8+
{
9+
10+
protected function getRule(): Rule
11+
{
12+
return new DisallowedEmptyRule();
13+
}
14+
15+
public function testRule(): void
16+
{
17+
$this->analyse([__DIR__ . '/data/empty.php'], [
18+
[
19+
'Construct empty() is not allowed. Use more strict comparison.',
20+
3,
21+
],
22+
]);
23+
}
24+
25+
}

Diff for: tests/Rules/DisallowedConstructs/data/empty.php

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?php
2+
3+
if (empty($test)) {
4+
5+
}

0 commit comments

Comments
 (0)