• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

sanmai / phpstan-rules / 16053408098

03 Jul 2025 02:38PM UTC coverage: 93.388% (-1.7%) from 95.082%
16053408098

Pull #5

github

web-flow
Merge f460393dc into ef5046d0d
Pull Request #5: Only flags loops where the ONLY content is an if statement

23 of 25 new or added lines in 1 file covered. (92.0%)

2 existing lines in 1 file now uncovered.

113 of 121 relevant lines covered (93.39%)

8.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.1
/src/Rules/RequireGuardClausesInLoopsRule.php
1
<?php
2

3
/**
4
 * Copyright 2025 Alexey Kopytko <alexey@kopytko.com>
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18

19
declare(strict_types=1);
20

21
namespace Sanmai\PHPStanRules\Rules;
22

23
use PhpParser\Node;
24
use PhpParser\Node\Expr\Throw_;
25
use PhpParser\Node\Expr\Yield_;
26
use PhpParser\Node\Expr\YieldFrom;
27
use PhpParser\Node\Stmt;
28
use PhpParser\Node\Stmt\Do_;
29
use PhpParser\Node\Stmt\Expression;
30
use PhpParser\Node\Stmt\For_;
31
use PhpParser\Node\Stmt\Foreach_;
32
use PhpParser\Node\Stmt\If_;
33
use PhpParser\Node\Stmt\Return_;
34
use PhpParser\Node\Stmt\While_;
35
use PHPStan\Analyser\Scope;
36
use PHPStan\Rules\Rule;
37
use PHPStan\Rules\RuleErrorBuilder;
38
use Override;
39

40
use function count;
41

42
/**
43
 * @implements Rule<Node>
44
 */
45
final class RequireGuardClausesInLoopsRule implements Rule
46
{
47
    public const ERROR_MESSAGE = 'Use guard clauses instead of wrapping code in if statements. Consider using: if (!condition) { continue; }';
48

49
    #[Override]
50
    public function getNodeType(): string
51
    {
52
        return Node::class;
16✔
53
    }
54

55
    /**
56
     * @return list<\PHPStan\Rules\IdentifierRuleError>
57
     */
58
    #[Override]
59
    public function processNode(Node $node, Scope $scope): array
60
    {
61
        if (!$this->isLoopNode($node)) {
16✔
62
            return [];
16✔
63
        }
64

65
        $statements = $this->getLoopStatements($node);
12✔
66
        if (null === $statements || [] === $statements) {
12✔
UNCOV
67
            return [];
×
68
        }
69

70
        if (1 !== count($statements)) {
12✔
71
            return [];
8✔
72
        }
73

74

75
        if (!$statements[0] instanceof If_) {
8✔
NEW
76
            return [];
×
77
        }
78

79
        // Simple rule: if the loop body is ONLY an if statement, flag it
80
        $ifStatement = $statements[0];
8✔
81

82
        // Exception: Allow if the if body contains only return, yield, or throw
83
        if ($this->containsOnlyReturnYieldOrThrow($ifStatement->stmts)) {
8✔
84
            return [];
4✔
85
        }
86

87
        return [
8✔
88
            RuleErrorBuilder::message(self::ERROR_MESSAGE)
8✔
89
                ->identifier('sanmai.requireGuardClauses')
8✔
90
                ->line($ifStatement->getLine())
8✔
91
                ->build(),
8✔
92
        ];
8✔
93
    }
94

95
    /**
96
     * @phpstan-assert-if-true For_|Foreach_|While_|Do_ $node
97
     * @psalm-assert-if-true For_|Foreach_|While_|Do_ $node
98
     */
99
    private function isLoopNode(Node $node): bool
100
    {
101
        return $node instanceof For_
16✔
102
            || $node instanceof Foreach_
16✔
103
            || $node instanceof While_
16✔
104
            || $node instanceof Do_;
16✔
105
    }
106

107
    private function isAllowedStatement(Node $statement): bool
108
    {
109
        // Skip empty statements
110
        if ($statement instanceof Stmt\Nop) {
8✔
111
            return true;
4✔
112
        }
113

114
        // Direct return statement
115
        if ($statement instanceof Return_) {
8✔
116
            return true;
4✔
117
        }
118

119
        // Expression statement that might be yield, yield from, or throw
120
        if ($statement instanceof Expression) {
8✔
121
            $expr = $statement->expr;
8✔
122
            return $expr instanceof Yield_
8✔
123
                || $expr instanceof YieldFrom
8✔
124
                || $expr instanceof Throw_;
8✔
125
        }
126

NEW
127
        return false;
×
128
    }
129

130
    /**
131
     * @return array<Stmt>|null
132
     */
133
    private function getLoopStatements(Node $node): ?array
134
    {
135
        if (!$this->isLoopNode($node)) {
12✔
136
            return null;
×
137
        }
138

139
        return $node->stmts;
12✔
140
    }
141

142
    /**
143
     * @param array<Stmt> $statements
144
     */
145
    private function containsOnlyReturnYieldOrThrow(array $statements): bool
146
    {
147
        if ([] === $statements) {
8✔
UNCOV
148
            return false;
×
149
        }
150

151
        foreach ($statements as $statement) {
8✔
152
            if (!$this->isAllowedStatement($statement)) {
8✔
153
                return false;
8✔
154
            }
155
        }
156

157
        return true;
4✔
158
    }
159
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc