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

sanmai / phpstan-rules / 16260904356

14 Jul 2025 07:37AM UTC coverage: 98.276% (+3.8%) from 94.488%
16260904356

Pull #16

github

web-flow
Merge a4c43b401 into 0b3535e3f
Pull Request #16: Improve tests, fix bugs

14 of 14 new or added lines in 4 files covered. (100.0%)

2 existing lines in 1 file now uncovered.

114 of 116 relevant lines covered (98.28%)

44.9 hits per line

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

95.45
/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\Yield_;
25
use PhpParser\Node\Expr\YieldFrom;
26
use PhpParser\Node\Stmt;
27
use PhpParser\Node\Stmt\Do_;
28
use PhpParser\Node\Stmt\Expression;
29
use PhpParser\Node\Stmt\For_;
30
use PhpParser\Node\Stmt\Foreach_;
31
use PhpParser\Node\Stmt\If_;
32
use PhpParser\Node\Stmt\While_;
33
use PHPStan\Analyser\Scope;
34
use PHPStan\Rules\Rule;
35
use PHPStan\Rules\RuleErrorBuilder;
36
use Override;
37

38
use function count;
39

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

47
    #[Override]
48
    public function getNodeType(): string
49
    {
50
        return Stmt::class;
84✔
51
    }
52

53
    /**
54
     * @return list<\PHPStan\Rules\IdentifierRuleError>
55
     */
56
    #[Override]
57
    public function processNode(Node $node, Scope $scope): array
58
    {
59
        $statements = $this->getLoopStatements($node);
84✔
60
        if (null === $statements || [] === $statements) {
84✔
61
            return [];
84✔
62
        }
63

64
        if (1 !== count($statements)) {
72✔
65
            return [];
48✔
66
        }
67

68

69
        if (!$statements[0] instanceof If_) {
48✔
UNCOV
70
            return [];
×
71
        }
72

73
        // Simple rule: if the loop body is ONLY an if statement, flag it
74
        $ifStatement = $statements[0];
48✔
75

76
        // Exception: Allow if the if body contains only return, yield, or throw
77
        if ($this->containsOnlyOneStatement($ifStatement->stmts)) {
48✔
78
            return [];
36✔
79
        }
80

81
        return [
48✔
82
            RuleErrorBuilder::message(self::ERROR_MESSAGE)
48✔
83
                ->identifier('sanmai.requireGuardClauses')
48✔
84
                ->line($ifStatement->getLine())
48✔
85
                ->build(),
48✔
86
        ];
48✔
87
    }
88

89
    /**
90
     * @phpstan-assert-if-true For_|Foreach_|While_|Do_ $node
91
     * @psalm-assert-if-true For_|Foreach_|While_|Do_ $node
92
     */
93
    private function isLoopNode(Node $node): bool
94
    {
95
        if ($node instanceof For_) {
84✔
96
            return true;
36✔
97
        }
98

99
        if ($node instanceof Foreach_) {
84✔
100
            return true;
72✔
101
        }
102

103
        if ($node instanceof While_) {
84✔
104
            return true;
36✔
105
        }
106

107
        if ($node instanceof Do_) {
84✔
108
            return true;
24✔
109
        }
110

111
        return false;
84✔
112
    }
113

114
    private function isYieldOrYieldFrom(Node $statement): bool
115
    {
116
        // Yield statements are always wrapped in Expression nodes
117
        if ($statement instanceof Expression) {
48✔
118
            return $statement->expr instanceof Yield_
48✔
119
                    || $statement->expr instanceof YieldFrom;
48✔
120
        }
121

122
        return false;
36✔
123
    }
124

125
    /**
126
     * @return array<Stmt>|null
127
     */
128
    private function getLoopStatements(Node $node): ?array
129
    {
130
        if (!$this->isLoopNode($node)) {
84✔
131
            return null;
84✔
132
        }
133

134
        return $node->stmts;
72✔
135
    }
136

137
    /**
138
     * @param array<Stmt> $statements
139
     */
140
    private function containsOnlyOneStatement(array $statements): bool
141
    {
142
        if ([] === $statements) {
48✔
UNCOV
143
            return false;
×
144
        }
145

146
        $count = 0;
48✔
147
        foreach ($statements as $statement) {
48✔
148
            if ($this->isYieldOrYieldFrom($statement)) {
48✔
149
                // Allow as many yields as needed, but with only one following statement
150
                $count = 0;
36✔
151
                continue;
36✔
152
            }
153

154
            $count++;
48✔
155

156
            if ($count > 1) {
48✔
157
                return false; // More than one statement found
48✔
158
            }
159
        }
160

161
        return true;
36✔
162
    }
163
}
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