• 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

98.37
/src/Rules/Functions/ArrayFirstLastNotationRule.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\Functions;
9

10
use DressCode\Analyses\Types;
11
use DressCode\{CodeWriter, Decision, Domain, GlobalCalls, NodeRule, RuleContext, RuleInfo, Stage, Tristate};
12
use DressCode\Rules\NodeHelpers;
13
use PhpSyntax\Analyses\NameResolver;
14
use PhpSyntax\{Builder, Node, Token};
15
use PhpSyntax\Nodes\{Expression, ExpressionNode, NameNode, PlainNodeList, Scalar};
16
use PhpSyntax\Nodes\Statement\ExpressionStatementNode;
17
use function count;
18

19

20
/**
21
 * The first or the last element of an array is read with `array_first()` and `array_last()` of PHP 8.5,
22
 * however the code reaches for it today: `reset($a)`, `end($a)`, `$a[array_key_first($a)]`,
23
 * `$a[array_key_last($a)]`, `array_values($a)[0]` and `array_values($a)[count($a) - 1]`. An array the code
24
 * spells twice must be the same expression and free of side effects, because the call reads it once.
25
 *
26
 * `reset()` and `end()` are a risky subject: they move the internal pointer of the array, which the new
27
 * functions leave where it is, and they answer an empty array with false where the new ones answer null.
28
 * The pointer is no risk where the call is the last read of a local variable (`NodeHelpers::isLastRead()`), and
29
 * the empty array none where the types say the array has an item; without the types, an array with an item is not
30
 * told from one that may be empty. A call of theirs whose value nothing takes is left alone, being there for the
31
 * pointer. A ternary choosing the call where the array has an item and null otherwise is the new function alone,
32
 * `$a ? reset($a) : null` being `array_first($a)`, and a variable holding an array only to pass it by reference,
33
 * `$x = explode(…); $x = end($x);`, gives way to the call taking the array itself.
34
 */
35
#[RuleInfo(Stage::Structure, requires: ['php' => '>=8.5'], analyses: [Types::class, NameResolver::class])]
36
final class ArrayFirstLastNotationRule extends NodeRule
37
{
38
        public static function getDecisions(): array
39
        {
40
                return [new Decision(
1 ✔
41
                        'upgrading.functions.arrayFirstLast',
1 ✔
42
                        Domain::state('required'),
1 ✔
43
                        '`array_first()`, `array_last()` for `reset()`, `end()` read as an item',
1 ✔
44
                )];
45
        }
46

47

48
        public function getVisitedNodes(): array
49
        {
50
                return [
51
                        Expression\FunctionCallNode::class,
1 ✔
52
                        Expression\ArrayAccessNode::class,
53
                        Expression\TernaryNode::class,
54
                        ExpressionStatementNode::class,
55
                ];
56
        }
57

58

59
        public function enter(Node|Token $node, RuleContext $context): void
60
        {
61
                // a call a ternary guards is read with the ternary, and one giving a variable held only for the reference its next
62
                // value with its statement: the rewrite replaces them
63
                $call = match (true) {
1 ✔
64
                        $node instanceof Expression\TernaryNode => $node->then instanceof Expression\FunctionCallNode ? $node->then : $node->else,
1 ✔
65
                        $node instanceof ExpressionStatementNode && $node->expression instanceof Expression\AssignmentNode
1 ✔
66
                                => $node->expression->expression,
1 ✔
67
                        default => $node,
1 ✔
68
                };
69
                $found = match (true) {
1 ✔
70
                        $call instanceof Expression\FunctionCallNode => self::readPointerCall($call, $context),
1 ✔
71
                        $call instanceof Expression\ArrayAccessNode => self::readOffset($call, $context),
1 ✔
72
                        default => null,
1 ✔
73
                };
74
                if ($found === null || !$node instanceof Node || $node->hasInnerComment()) {
1 ✔
75
                        return;
1 ✔
76
                }
77

78
                [$function, $array, $replaced] = $found;
1 ✔
79
                $pointerCall = $call instanceof Expression\FunctionCallNode;
1 ✔
80
                $guard = $pointerCall ? self::findGuardingTernary($call, $array, $context) : null;
1 ✔
81
                $temporary = $pointerCall ? self::findTemporaryAssignment($call, $array) : null;
1 ✔
82
                $rewritten = match (true) {
1 ✔
83
                        $guard !== null => $guard,
1 ✔
84
                        $temporary !== null => $call->parent?->parent,
1 ✔
85
                        default => $call,
1 ✔
86
                };
87
                if ($node !== $rewritten) {
1 ✔
88
                        return;
1 ✔
89
                }
90

91
                $uncertainty = GlobalCalls::findUncertaintyOfRewrite($call, [$array], $context);
1 ✔
92
                $element = $function === 'array_first' ? 'first' : 'last';
1 ✔
93
                $pointerMatters = $pointerCall
1 ✔
94
                        && !($array instanceof Expression\VariableNode && NodeHelpers::isLastRead($array, $call, $context));
1 ✔
95
                $emptyMatters = $pointerCall
1 ✔
96
                        && $guard === null
1 ✔
97
                        && $context->findAnalysis(Types::class)?->isOfType($array, 'non-empty-array') !== Tristate::Yes;
1 ✔
98
                $because = match (true) {
1 ✔
99
                        $pointerMatters && $emptyMatters => '`reset()` and `end()` move the pointer of the array and return false for an empty one',
1 ✔
100
                        $pointerMatters => '`reset()` and `end()` move the pointer of the array',
1 ✔
101
                        $emptyMatters => '`reset()` and `end()` return false for an empty array',
1 ✔
102
                        default => null,
1 ✔
103
                };
104
                if (!$context->report(
1 ✔
105
                        $call,
106
                        "The $element item must be read with `$function()`.",
1 ✔
107
                        risk: NodeHelpers::findRisk($because, $uncertainty),
1 ✔
108
                        because: $because ?? $uncertainty,
1 ✔
109
                )) {
110
                        return;
1 ✔
111
                }
112

113
                $spelling = CodeWriter::spellFunction($function, $replaced, $context);
1 ✔
114
                if ($temporary !== null) { // the value the variable held only to be passed by reference
1 ✔
115
                        $temporary->expression = (new Builder)->call($spelling, [$temporary->expression]);
1 ✔
116
                        NodeHelpers::removeMergingGaps($node, $context->style->lineEnding);
1 ✔
117
                } else {
118
                        $node->replaceWith((new Builder)->call($spelling, [$array]));
1 ✔
119
                }
120
        }
1 ✔
121

122

123
        /**
124
         * The ternary choosing the call only where the array has an item and null otherwise, which the new function answers
125
         * alone: `$a ? reset($a) : null`, the array tested as `!$a`, `$a !== []`, `count($a) > 0`, `empty($a)` and their kin too.
126
         */
127
        private static function findGuardingTernary(
128
                Expression\FunctionCallNode $call,
129
                ExpressionNode $array,
130
                RuleContext $context,
131
        ): ?Expression\TernaryNode
132
        {
133
                $ternary = $call->parent;
1 ✔
134
                if (!$ternary instanceof Expression\TernaryNode || $ternary->then === null) {
1 ✔
135
                        return null;
1 ✔
136
                }
137

138
                $condition = $ternary->condition;
1 ✔
139
                $negated = $condition instanceof Expression\UnaryOpNode && $condition->operator->is('!');
1 ✔
140
                $condition = $negated ? $condition->expression : $condition;
1 ✔
141
                $hasItems = match (true) {
1 ✔
142
                        NodeHelpers::isRepeatedRead($condition, $array),
1 ✔
143
                        NodeHelpers::isRepeatedRead(NodeHelpers::findSingleArgument($condition, 'count', $context), $array) => true,
1 ✔
144
                        $condition instanceof Expression\EmptyNode && NodeHelpers::isRepeatedRead($condition->expression, $array) => false,
1 ✔
145
                        $condition instanceof Expression\BinaryOpNode
1 ✔
146
                                && $condition->operator->is([Token::IsIdentical, Token::IsNotIdentical])
1 ✔
147
                                && $condition->right instanceof Expression\ArrayNode
1 ✔
148
                                && count($condition->right->items) === 0
1 ✔
149
                                && NodeHelpers::isRepeatedRead($condition->left, $array) => $condition->operator->is(Token::IsNotIdentical),
1 ✔
150
                        $condition instanceof Expression\BinaryOpNode
1 ✔
151
                                && $condition->operator->is([Token::IsIdentical, '>'])
1 ✔
152
                                && NodeHelpers::isInteger($condition->right, 0)
1 ✔
153
                                && NodeHelpers::isRepeatedRead(NodeHelpers::findSingleArgument($condition->left, 'count', $context), $array)
1 ✔
154
                                => $condition->operator->is('>'),
1 ✔
UNCOV
155
                        default => null,
×
156
                };
157
                if ($hasItems === null) {
1 ✔
UNCOV
158
                        return null;
×
159
                }
160

161
                [$chosen, $other] = $hasItems !== $negated ? [$ternary->then, $ternary->else] : [$ternary->else, $ternary->then];
1 ✔
162
                return $chosen === $call && $other instanceof Scalar\NullNode ? $ternary : null;
1 ✔
163
        }
164

165

166
        /**
167
         * The assignment of the statement right before the one where the call gives the variable its next value, `$x = …;`
168
         * above `$x = end($x);`, which then takes the call itself; null where anything else, a comment too, stands between.
169
         */
170
        private static function findTemporaryAssignment(Expression\FunctionCallNode $call, ExpressionNode $array): ?Expression\AssignmentNode
171
        {
172
                $assignment = $call->parent;
1 ✔
173
                $statement = $assignment?->parent;
1 ✔
174
                $name = $array instanceof Expression\VariableNode ? $array->plainName : null;
1 ✔
175
                $isVariable = fn(?Node $node) => $name !== null && $node instanceof Expression\VariableNode && $node->plainName === $name;
1 ✔
176
                if (
177
                        !$assignment instanceof Expression\AssignmentNode
1 ✔
178
                        || $assignment->expression !== $call
1 ✔
179
                        || !$isVariable($assignment->target)
1 ✔
180
                        || !$statement instanceof ExpressionStatementNode
1 ✔
181
                        || !$statement->parent instanceof PlainNodeList
1 ✔
182
                ) {
183
                        return null;
1 ✔
184
                }
185

186
                $previous = $statement->getPreviousSibling();
1 ✔
187
                return $previous instanceof ExpressionStatementNode
1 ✔
188
                        && $previous->expression instanceof Expression\AssignmentNode
1 ✔
189
                        && $isVariable($previous->expression->target)
1 ✔
190
                        && !$previous->hasTrailingComment()
1 ✔
191
                        && !$statement->hasLeadingComment()
1 ✔
192
                        ? $previous->expression
1 ✔
193
                        : null;
1 ✔
194
        }
195

196

197
        /**
198
         * The array a call of `reset()` or `end()` reads the edge element of, where something takes the value, and the
199
         * name of the call.
200
         * @return ?array{string, ExpressionNode, NameNode|ExpressionNode}
201
         */
202
        private static function readPointerCall(Expression\FunctionCallNode $call, RuleContext $context): ?array
203
        {
204
                $function = match (GlobalCalls::findFunction($call, ['reset' => true, 'end' => true], $context)) {
1 ✔
205
                        'reset' => 'array_first',
1 ✔
206
                        'end' => 'array_last',
1 ✔
207
                        default => null,
1 ✔
208
                };
209
                $arguments = $function === null ? null : $call->arguments->getPlainValues();
1 ✔
210
                return $arguments === null || count($arguments) !== 1 || $call->parent instanceof ExpressionStatementNode
1 ✔
211
                        ? null
1 ✔
212
                        : [$function, $arguments[0], $call->name];
1 ✔
213
        }
214

215

216
        /**
217
         * The array an offset access reads the edge element of, by the key the edge has or by the position it
218
         * takes among the values, and the name of the call that is replaced.
219
         * @return ?array{string, ExpressionNode, NameNode|ExpressionNode}
220
         */
221
        private static function readOffset(ExpressionNode $access, RuleContext $context): ?array
222
        {
223
                // a call gives a value, never the place the code writes to, unsets or asks `isset()` about
224
                if (
225
                        !$access instanceof Expression\ArrayAccessNode
1 ✔
226
                        || $access->index === null
1 ✔
227
                        || (!$access->index instanceof Expression\FunctionCallNode && !$access->expression instanceof Expression\FunctionCallNode)
1 ✔
228
                        || $access->isWritten()
1 ✔
229
                        || self::isIssetOperand($access)
1 ✔
230
                ) {
231
                        return null;
1 ✔
232
                }
233

234
                // $a[array_key_first($a)]
235
                foreach (['array_key_first' => 'array_first', 'array_key_last' => 'array_last'] as $key => $function) {
1 ✔
236
                        $keyed = NodeHelpers::findSingleArgument($access->index, $key, $context);
1 ✔
237
                        if ($keyed !== null && NodeHelpers::isRepeatedRead($keyed, $access->expression)) {
1 ✔
238
                                assert($access->index instanceof Expression\FunctionCallNode);
239
                                return [$function, $access->expression, $access->index->name];
1 ✔
240
                        }
241
                }
242

243
                // array_values($a)[0] and array_values($a)[count($a) - 1]
244
                $array = NodeHelpers::findSingleArgument($access->expression, 'array_values', $context);
1 ✔
245
                if ($array === null) {
1 ✔
246
                        return null;
1 ✔
247
                }
248

249
                assert($access->expression instanceof Expression\FunctionCallNode);
250
                if (NodeHelpers::isInteger($access->index, 0)) {
1 ✔
251
                        return ['array_first', $array, $access->expression->name];
1 ✔
252
                }
253

254
                return NodeHelpers::isRepeatedRead(NodeHelpers::findCountedArray($access->index, $context), $array)
1 ✔
255
                        ? ['array_last', $array, $access->expression->name]
1 ✔
256
                        : null;
1 ✔
257
        }
258

259

260
        private static function isIssetOperand(ExpressionNode $expression): bool
261
        {
262
                $node = $expression->parent;
1 ✔
263
                while ($node instanceof Expression\ParenthesizedNode) {
1 ✔
264
                        $node = $node->parent;
1 ✔
265
                }
266

267
                return $node?->parent instanceof Expression\IssetNode;
1 ✔
268
        }
269
}
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