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

dg / dresscode / 42439021063

08 Nov 2026 02:24AM UTC coverage: 96.937% (-0.002%) from 96.939%
42439021063

push

github

dg
long lines: the head of a foreach too wide spreads what it iterates before what it assigns

Of two constructs on a line with no common one to spread the last spreads first, so a `foreach` iterating a long
array literal spread the destructuring after `as` and kept the array whole, `[…] as [` above `$location,`. What
a `foreach` iterates now spreads first, its measure not looking past the `as`, and what it assigns waits while the
iterated expression on its line has something to spread, spreading only where the line left, `] as [$a, $b]) {`, is
still too wide; what follows the iterated expression no longer keeps it from spreading, the destructuring spreading
next. The search for a split beginning at a token is shared, `NodeHelpers::beginsSplit()`.

b243d2e8-3e44-4152-8c16-82d9156e6db2

33 of 36 new or added lines in 1 file covered. (91.67%)

96 existing lines in 23 files now uncovered.

30032 of 30981 relevant lines covered (96.94%)

0.97 hits per line

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

96.12
/src/Rules/ControlFlow/NoAlternativeSyntaxRule.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the DressCode, a coding style and upgrade tool for PHP (https://dresscode.run)
5
 * Copyright (c) 2026 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace DressCode\Rules\ControlFlow;
9

10
use DressCode\{Decision, Domain, NodeRule, RuleContext, RuleInfo, Stage};
11
use PhpSyntax\{Builder, Node, Token, Trivia};
12
use PhpSyntax\Nodes\{CaseNode, ElseifNode, ElseNode, PlainNodeList, StatementNode};
13
use PhpSyntax\Nodes\Statement\{
14
        BlockNode, DeclareNode, EmptyStatementNode, ForeachNode, ForNode, IfNode, InlineHtmlNode, SwitchNode, WhileNode,
15
};
16

17

18
/**
19
 * Braces instead of the alternative syntax: `if (...) {` … `}`, not `if (...):` … `endif;`. A structure a template
20
 * writes around markup, a body of any of its branches holding the text between `?>` and `<?php`, keeps it whole.
21
 */
22
#[RuleInfo(Stage::Structure)]
23
final class NoAlternativeSyntaxRule extends NodeRule
24
{
25
        public static function getDecisions(): array
26
        {
27
                return [new Decision(
1 ✔
28
                        'braces.alternativeSyntax',
1 ✔
29
                        Domain::state('forbidden'),
1 ✔
30
                        '`if: … endif;` is written with braces, a structure a template writes around markup excepted',
1 ✔
31
                )];
32
        }
33

34

35
        public function getVisitedNodes(): array
36
        {
37
                return [IfNode::class, WhileNode::class, ForNode::class, ForeachNode::class, SwitchNode::class, DeclareNode::class];
1 ✔
38
        }
39

40

41
        public function enter(Node|Token $node, RuleContext $context): void
42
        {
43
                [$colon, $semicolon] = match (true) {
1 ✔
44
                        $node instanceof IfNode,
1 ✔
45
                        $node instanceof WhileNode,
1 ✔
46
                        $node instanceof ForNode,
1 ✔
47
                        $node instanceof ForeachNode,
1 ✔
48
                        $node instanceof SwitchNode,
1 ✔
49
                        $node instanceof DeclareNode => [$node->colon, $node->semicolon],
1 ✔
50
                        default => [null, null],
1 ✔
51
                };
52
                // a close tag closes the statement instead of a semicolon and the braces cannot swallow it
53
                $closeTag = $semicolon?->is(Token::CloseTag) ? $semicolon : null;
1 ✔
54
                $fixable = $closeTag === null || $node->parent instanceof PlainNodeList;
1 ✔
55
                if (
56
                        $colon === null
1 ✔
57
                        || !$node instanceof Node
1 ✔
58
                        || self::enclosesMarkup($node)
1 ✔
59
                        // braces would hand it the `else` of the enclosing `if:`, which keeps its syntax
60
                        || ($node instanceof IfNode && $node->else === null && $node->getLastToken()->getNext()?->is([Token::Else, Token::Elseif]))
1 ✔
61
                        || !$context->report(
1 ✔
62
                                $colon,
1 ✔
63
                                'The `'
64
                                        . strtolower((string) $node->getFirstToken()?->text)
1 ✔
65
                                        . '` must be written with braces instead of the alternative syntax.',
1 ✔
66
                                fixable: $fixable,
67
                        )
68
                        || !$fixable
1 ✔
69
                ) {
70
                        return;
1 ✔
71
                }
72

73
                if ($node instanceof SwitchNode) {
1 ✔
74
                        self::rewriteSwitch($node, $closeTag);
1 ✔
75

76
                } elseif ($node instanceof IfNode) {
1 ✔
77
                        self::rewriteIf($node, $closeTag);
1 ✔
78

79
                } elseif (
80
                        $node instanceof WhileNode
1 ✔
81
                        || $node instanceof ForNode
1 ✔
82
                        || $node instanceof ForeachNode
1 ✔
83
                        || $node instanceof DeclareNode
1 ✔
84
                ) {
85
                        $end = $node->endKeyword;
1 ✔
86
                        if ($end === null || $node->statements === null) {
1 ✔
UNCOV
87
                                return;
×
88
                        }
89

90
                        $block = self::buildBlock(
1 ✔
91
                                $colon,
1 ✔
92
                                $node->statements,
1 ✔
93
                                $end->leadingTrivia,
1 ✔
94
                                ($closeTag === null ? $semicolon ?? $end : $end)->trailingTrivia,
1 ✔
95
                        );
96
                        $node->colon = null;
1 ✔
97
                        $node->statements = null;
1 ✔
98
                        $node->endKeyword = null;
1 ✔
99
                        $node->semicolon = null;
1 ✔
100
                        $node->body = $block;
1 ✔
101
                        self::keepCloseTag($node, $closeTag);
1 ✔
102
                }
103
        }
1 ✔
104

105

106
        /**
107
         * Whether a body of the structure, of any of its branches or cases, holds markup between `?>` and `<?php`, which
108
         * a template writes the alternative syntax around.
109
         */
110
        private static function enclosesMarkup(Node $node): bool
111
        {
112
                $bodies = match (true) {
1 ✔
113
                        $node instanceof IfNode => array_map(
1 ✔
114
                                fn(IfNode|ElseifNode|ElseNode $branch) => $branch->statements,
1 ✔
115
                                [$node, ...$node->elseifs->getItems(), ...($node->else !== null ? [$node->else] : [])],
1 ✔
116
                        ),
117
                        $node instanceof SwitchNode => array_map(fn(CaseNode $case) => $case->statements, $node->cases->getItems()),
1 ✔
118
                        $node instanceof WhileNode, $node instanceof ForNode, $node instanceof ForeachNode, $node instanceof DeclareNode
1 ✔
119
                                => [$node->statements],
1 ✔
UNCOV
120
                        default => [],
×
121
                };
122
                return array_any(
1 ✔
123
                        $bodies,
124
                        fn(?PlainNodeList $statements) => array_any($statements?->getItems() ?? [], fn(Node $stmt) => $stmt instanceof InlineHtmlNode),
1 ✔
125
                );
126
        }
127

128

129
        private static function rewriteIf(IfNode $node, ?Token $closeTag): void
130
        {
131
                $end = $node->endKeyword;
1 ✔
132
                if ($end === null) {
1 ✔
UNCOV
133
                        return;
×
134
                }
135

136
                $last = $closeTag === null ? $node->semicolon ?? $end : $end;
1 ✔
137

138
                $branches = [$node, ...$node->elseifs->getItems(), ...($node->else !== null ? [$node->else] : [])];
1 ✔
139
                foreach ($branches as $i => $branch) {
1 ✔
140
                        if ($branch->colon === null || $branch->statements === null) {
1 ✔
UNCOV
141
                                continue;
×
142
                        }
143

144
                        $next = $branches[$i + 1] ?? null;
1 ✔
145
                        $nextKeyword = match (true) {
1 ✔
146
                                $next instanceof ElseifNode => $next->elseifKeyword,
1 ✔
147
                                $next instanceof ElseNode => $next->elseKeyword,
1 ✔
148
                                default => null,
1 ✔
149
                        };
150
                        [$closeLeading, $closeTrailing] = $nextKeyword !== null
1 ✔
151
                                ? [$nextKeyword->leadingTrivia, [Trivia::fromText(' ')]]
1 ✔
152
                                : [$end->leadingTrivia, $last->trailingTrivia];
1 ✔
153
                        $block = self::buildBlock($branch->colon, $branch->statements, $closeLeading, $closeTrailing);
1 ✔
154
                        if ($nextKeyword !== null) {
1 ✔
155
                                $nextKeyword->setLeadingTrivia([]);
1 ✔
156
                        }
157

158
                        $branch->colon = null;
1 ✔
159
                        $branch->statements = null;
1 ✔
160
                        $branch->body = $block;
1 ✔
161
                }
162

163
                $node->endKeyword = null;
1 ✔
164
                $node->semicolon = null;
1 ✔
165
                self::keepCloseTag($node, $closeTag);
1 ✔
166
        }
1 ✔
167

168

169
        private static function rewriteSwitch(SwitchNode $node, ?Token $closeTag): void
170
        {
171
                $end = $node->endKeyword;
1 ✔
172
                $colon = $node->colon;
1 ✔
173
                if ($end === null || $colon === null) {
1 ✔
UNCOV
174
                        return;
×
175
                }
176

177
                $last = $closeTag === null ? $node->semicolon ?? $end : $end;
1 ✔
178
                self::ensureSpaceBefore($colon);
1 ✔
179
                $openBrace = Token::fromText('{')
1 ✔
180
                        ->setLeadingTrivia($colon->leadingTrivia)
1 ✔
181
                        ->setTrailingTrivia($colon->trailingTrivia);
1 ✔
182
                $closeBrace = Token::fromText('}')
1 ✔
183
                        ->setLeadingTrivia($end->leadingTrivia)
1 ✔
184
                        ->setTrailingTrivia($last->trailingTrivia);
1 ✔
185
                $node->colon = null;
1 ✔
186
                $node->endKeyword = null;
1 ✔
187
                $node->semicolon = null;
1 ✔
188
                $node->openBrace = $openBrace;
1 ✔
189
                $node->closeBrace = $closeBrace;
1 ✔
190
                self::keepCloseTag($node, $closeTag);
1 ✔
191
        }
1 ✔
192

193

194
        /**
195
         * The close tag that ended the alternative syntax lives on as a statement of its own,
196
         * the way the parser reads it after a block.
197
         */
198
        private static function keepCloseTag(StatementNode $node, ?Token $closeTag): void
199
        {
200
                if ($closeTag === null || !($list = $node->parent) instanceof PlainNodeList) {
1 ✔
201
                        return;
1 ✔
202
                }
203

204
                $statement = (new Builder)->fragment(EmptyStatementNode::class, '?' . '>');
1 ✔
205
                $statement->semicolon
1 ✔
206
                        ->setText($closeTag->text)
1 ✔
207
                        ->setLeadingTrivia($closeTag->leadingTrivia)
1 ✔
208
                        ->setTrailingTrivia($closeTag->trailingTrivia);
1 ✔
209
                $list->insertAfter($node, $statement);
1 ✔
210
        }
1 ✔
211

212

213
        /**
214
         * @param PlainNodeList<StatementNode> $stmts
215
         * @param list<Trivia> $closeLeading
216
         * @param list<Trivia> $closeTrailing
217
         */
218
        private static function buildBlock(Token $colon, PlainNodeList $stmts, array $closeLeading, array $closeTrailing): BlockNode
219
        {
220
                self::ensureSpaceBefore($colon);
1 ✔
221
                $block = (new Builder)->fragment(BlockNode::class, '{}');
1 ✔
222
                $block->openBrace
1 ✔
223
                        ->setLeadingTrivia($colon->leadingTrivia)
1 ✔
224
                        ->setTrailingTrivia($colon->trailingTrivia);
1 ✔
225
                $block->closeBrace
1 ✔
226
                        ->setLeadingTrivia($closeLeading)
1 ✔
227
                        ->setTrailingTrivia($closeTrailing);
1 ✔
228
                foreach ($stmts->getItems() as $stmt) {
1 ✔
229
                        $stmts->removeItem($stmt);
1 ✔
230
                        $block->statements->append($stmt);
1 ✔
231
                }
232

233
                return $block;
1 ✔
234
        }
235

236

237
        /**
238
         * The colon sits right after the closing parenthesis; the brace replacing it wants a space before.
239
         */
240
        private static function ensureSpaceBefore(Token $colon): void
241
        {
242
                $previous = $colon->getPrevious();
1 ✔
243
                if ($previous?->getTrailingSpace() === '' && $colon->leadingTrivia === []) {
1 ✔
244
                        $previous->setTrailingSpace(' ');
1 ✔
245
                }
246
        }
1 ✔
247
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc