Repository navigation
Flag and, or and xor directly after an assignment - #401
mikebronner merged 4 commits into
Conversation
Watson-Branch: #399
PHP binds and, or and xor looser than every assignment operator, so `$granted = $isOwner or $isAdmin;` assigns only `$isOwner`. The new CleanCode.Operators.LogicalKeywordAfterAssignment sniff reports each such keyword at the top level of a statement that starts with an assignment, at error severity and with no fixer. Declarations (const, class constants, property defaults, enum cases, static initializers), keywords inside parentheses, arrays, match arms and arrow function bodies, and conditions already covered by Generic.CodeAnalysis.AssignmentInCondition stay silent. Fixes: #399
There was a problem hiding this comment.
🔄 Changes Requested
All 21 acceptance criteria are met, and CI is green on 8.3, 8.4 and 8.5. Four gaps in the new code block the merge. Three are untested routes: each lets a regression silence a real violation while the suite still passes. Each was checked by an attacker, a defender and an auditor, except the target-token gap, which a single skeptic checked.
Issues Found
-
The skip route over a closure,
matchor anonymous-class body has no fixture.LogicalKeywordAfterAssignmentSniff.php:193-201and:242-256. The only}any fixture walk reaches is theswitchcloser atfailing.php:68, which takes the not-an-expression-scope branch. Nothing reachesreturn $tokens[$closer]['scope_opener'](:255) or thebracket_openerfallback (:248). If either returned null, these statements would go silent. Add tofailing.php, each expecting one report on theor:$x = match ($a) { default => 1 } or $b;$f = function () {} or $b;$o = new class {} or $b;$a = $o->{$name} or $b;
-
Braceless and alternative-syntax bodies are tested only for
if.BRACELESS_BODY_SCOPES(:51-60) drives:212and:231. The test atLogicalKeywordAfterAssignmentTest.php:163checks only the union of the three scope lists. MovingT_ELSEorT_FOREACHintoBLOCK_SCOPESwould pass the suite, andelse $a = $b or $c;would go unreported. The walk would run on to an earlier;, andstartsWithAssignmentwould then seeelse. Add tofailing.php, each expecting one report:else $a = $b or $d;after anifelseif ($c) $a = $b or $d;foreach ($l as $i) $a = $b or $d;while ($c) $a = $b or $d;for (;;) $a = $b or $d;do $a = $b or $d; while ($c);declare(ticks=1) $a = $b or $d;- an alternative-syntax body each for
foreach:,while:andelse:
-
Seven
TARGET_TOKENSmembers reach no fixture.:78-96. If any one is dropped,startsWithAssignmentreturns false at:274, and the statement goes silent. Add tofailing.php, each with an||form inpassing.php:$$a = $b or $c;(T_DOLLAR)${'a'} = $b or $c;(T_OPEN_CURLY_BRACKET)self::$p = $b or $c;parent::$p = $b or $c;Foo\Bar::$p = $b or $c;\Foo\Bar::$p = $b or $c;namespace\Foo::$p = $b or $c;
-
An unguarded array read aborts the sniff on a file with an unmatched closer.
:184reads$token['parenthesis_opener'] ?? $token['bracket_opener'].??guards only the left operand. A stray)or]has neither key, so PHP raises "Undefined array key", and PHPCS aborts that file's check with an internal error. If warnings were muted,$iwould become null, and the loop at:171would never end. Every other sniff in the repo guards this lookup, for exampleNPathComplexitySniff.php:315andRequireStringInterpolationSniff.php:362. Fix:?? $token['bracket_opener'] ?? null, and returnnullwhen it is null. Then add a malformed fixture, as the repo does intests/fixtures/ArrayAccessorsSniff/malformed.php. Use<?php $x = 1 ) and $y;and a]variant, and assert that the sniff completes and reports nothing.
What's Good
- The fixtures and test pin every AC shape tightly. The 47-tuple
toBecomparison gives an exact count. Full message text is asserted for all three keywords and their case variants, and the no-fixer check is byte-identical. - The sniff has no comments and no suppressions. The one-line change to
BooleanOperatorSpacingTest.phpis a needed shared-token entry. - One claim was checked and dropped. PHPCS folds an interpolated string or heredoc into a single string token, so
"x{$y}" or $bcannot stop the backward walk early.
📋 Non-blocking follow-ups
- None.
Please address the above and re-request review.
A stray `)` or `]` has no opener key, so the backward walk raised
"Undefined array key" and PHPCS aborted the file. The walk now stops
and reports nothing when a closer has no opener.
The fixtures now reach every route the walk takes: closure, match,
anonymous-class and `$o->{$name}` bodies, braceless and
alternative-syntax bodies for each control structure, and each
assignment-target token.
|
All four blockers are fixed in commit
|
There was a problem hiding this comment.
🔄 Changes Requested
All four round-1 blockers are fixed. All 21 acceptance criteria are met, and CI is green on 8.3, 8.4 and 8.5. Four gaps remain in the new sniff. Two are untested routes, each confirmed by a skeptic. The other two are reports the sniff misses. A skeptic confirmed both misses and called them out of scope. They are kept here because they are in the code this PR wrote, and each fix is one line plus a fixture. All four are listed in this round so that no further round is needed for walk coverage.
Issues Found
-
The guard that ignores a colon with no
scope_conditionis untested.LogicalKeywordAfterAssignmentSniff.php:223-228. Every colon the walk reaches in the fixtures is acase,defaultor alternative-syntax colon, and each of those has ascope_condition. If theissetguard were dropped, a closure's return-type colon would end the statement, and$f = function (): bool {} or $b;would go silent. Named functions atfailing.php:43and:77do not reach the colon, because the walk stops at their}. Add$f = function (): bool {} or $b;tofailing.php, expecting one report on theor, and the||form topassing.php. -
isDirectlyInParenthesesreturns true only when no scope owner exists.:152-165. This is the only guard for aforcondition, where the walk stops at the;insidefor (...). The fixture for it,passing.php:130, sits at file top level, so$scopeOpeneris always -1 there. The comparison with a scope owner present is reached only byfailing.php:84, and only on its false path. If that comparison broke,function f() { for ($i = 0; $a = $b or $c; $i++) {} }would be reported, and the suite would still pass. Add that shape topassing.php, expecting no report, and add a closure-body variant too. -
A statement after a goto label is silent.
:179,:271-283. PHPCS readsstart:as oneT_GOTO_LABELtoken. The walk passes it, andstartsWithAssignmentthen returns false on it, sostart: $a = $b or $c;is not reported. TreatT_GOTO_LABELas a statement boundary inendsPreviousStatement. Add that line tofailing.php, expecting one report. -
A leading
@silences the report.:78-96.T_ASPERANDis not inTARGET_TOKENS, so@$a = f() or die();returns false at the@. PHP runs that line as(@($a = f())) or die(), which is the bug this sniff exists to catch. SkipT_ASPERANDas a leading token. Add the line tofailing.php, expecting one report, and the||form topassing.php.
What's Good
- Every round-1 item is closed. The stray-closer guard at
:184-188returns null cleanly, and bothstray-*.phpfixtures pin it. The closure,match, anonymous-class and{$name}skips are now covered, and so are the braceless and alternative-syntax bodies of each control structure and the seven missing target tokens. - The exact-tuple assertion still gives an exact count, and every
failing.phpline is mirrored inpassing.php. - The sniff adds no comments and no suppressions. The multi-line
addErrorcall follows the repo's indentation rule. - The security and correctness lenses found no other defect. Both scans always end, and each jump lands on a lower index.
📋 Non-blocking follow-ups
- None.
Please address the above and re-request review.
… and for-condition guards. A goto colon now ends the previous statement, and a leading @ no longer hides the assignment. New fixtures reach the closure return-type colon, a use clause, a static or attributed closure, and a for condition inside a function or closure body.
|
All four round-2 blockers are fixed in commit
Sweep of the other tokens the backward walk crosses before a boundary: a closure
|
There was a problem hiding this comment.
✅ Approved
Review Summary
- Reviewed the round-3 head of the new
CleanCode.Operators.LogicalKeywordAfterAssignmentsniff, with its fixtures, behaviour test,SWEPT_SNIFFSentry and Boost reference. - All four round-2 blockers are fixed, and each has a fixture:
- A closure's return-type colon no longer ends the statement (
failing.php:132-135). - A
forcondition inside a function or closure body stays silent (passing.php:221-230). - A statement after a goto label is reported, at top level and in a function body (
failing.php:137,:139-143). - A leading
@is skipped, so@$a = f() or die();is reported (failing.php:145-146).@foo() or bar();stays silent.
- A closure's return-type colon no longer ends the statement (
- All 21 acceptance criteria are met. CI runs
composer lint,composer testandcomposer lint:self, and all three pass on 8.3, 8.4 and 8.5. The diff adds no suppression and no ruleset exclusion. - Each branch in the sniff is reached on both sides by a fixture. The exact-position test pins every report. Both scans always end, and every token-key read is guarded.
- Everything in the coherent unit is clean. The sniff adds no comments. Its multi-line
addErrorindentation matches the other sniffs inCleanCode/Sniffs/Metrics/.
📋 Non-blocking follow-ups
- None.
Ready for @mikebronner to merge.
Brings in the LogicalKeywordAfterAssignment sniff from #401. phpcbf splits two of its return statements so they pass the new multi-condition rule.
Summary
Implements #399
$granted = $isOwner or $isAdmin;assigns only$isOwner, because PHP bindsand,orandxorlooser than=. This adds a sniff that reports that shape.Changes
CleanCode.Operators.LogicalKeywordAfterAssignment, error severity, no fixer. It reports eachand,ororxorat the top level of a statement that starts with an assignment, on the keyword's own line and column.;, open or close tag, block brace, goto label,caseor alternative-syntax colon, or the closing)of a bracelessif/elseif/while/for/foreach/declare(pluselseanddo). A closure, anonymous class ormatchbefore the keyword is skipped as one expression. A)or]with no opener ends the walk with no report, so malformed source no longer aborts the file.matcharm, an arrow function body or a<?=tag, and when the statement starts with anything other than an assignment target (const, a visibility keyword,static $x,case,echo,return, a call, a(). A leading@is skipped, so@$a = f() or die();is reported.tests/fixtures/LogicalKeywordAfterAssignmentSniff/.passing.phpholds a&&/||twin of every reported shape, plus every silent shape.match, anonymous-class and$o->{$name}bodies, a closure with a return-type colon, auseclause,staticor an attribute, a statement after a goto label, a leading@, aforcondition inside a function or closure body, a braceless and an alternative-syntax body per control structure, and every assignment-target token ($$a,${'a'},self::,parent::, qualified, fully qualified andnamespace\names).stray-parenthesis.phpandstray-bracket.phppin the unmatched-closer stop.phpcbfleavesfailing.phpbyte-identical, and that each token-family constant partitions its PHPCS family (booleanOperators,assignmentTokens,scopeOpeners).SWEPT_SNIFFS. TheBooleanOperatorSpacingshared-token pin now lists the new sniff, since it registers on the same keywords for a different concern.operators-logical-keywords-after-assignment.md, linked fromSKILL.mdand the README's Standards list.One caveat: the criteria ask for a
$o?->ptarget. PHP rejects a nullsafe write at compile time, sophp -lfails on both fixtures. PHPCS tokenises the line fine, and the fixtures are never executed.Test Plan
composer testpasses (3047 tests)composer lintexits 0composer lint:selfexits 0, with 0 errors and no new error-level findingsFixes #399