Skip to content

Flag and, or and xor directly after an assignment - #401

Merged
mikebronner merged 4 commits into
mainfrom
feature/399-flag-and-or-and-xor-directly-after-an-assignment
Nov 13, 2026
Merged

mikebronner merged 4 commits into
mainfrom
feature/399-flag-and-or-and-xor-directly-after-an-assignment

Conversation

@mikebronner

@mikebronner mikebronner commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements #399

$granted = $isOwner or $isAdmin; assigns only $isOwner, because PHP binds and, or and xor looser than =. This adds a sniff that reports that shape.

Changes

  • New sniff CleanCode.Operators.LogicalKeywordAfterAssignment, error severity, no fixer. It reports each and, or or xor at the top level of a statement that starts with an assignment, on the keyword's own line and column.
  • A statement is found by walking back from the keyword to the previous ;, open or close tag, block brace, goto label, case or alternative-syntax colon, or the closing ) of a braceless if/elseif/while/for/foreach/declare (plus else and do). A closure, anonymous class or match before 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.
  • Silent when the keyword sits inside parentheses, brackets, a match arm, 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.
  • Fixtures under tests/fixtures/LogicalKeywordAfterAssignmentSniff/. passing.php holds a &&/|| twin of every reported shape, plus every silent shape.
  • The fixtures reach every route of that walk: closure, match, anonymous-class and $o->{$name} bodies, a closure with a return-type colon, a use clause, static or an attribute, a statement after a goto label, a leading @, a for condition 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 and namespace\ names). stray-parenthesis.php and stray-bracket.php pin the unmatched-closer stop.
  • Behaviour test asserts all 77 reports by line, column and source, the full message for each keyword in each source case, that phpcbf leaves failing.php byte-identical, and that each token-family constant partitions its PHPCS family (booleanOperators, assignmentTokens, scopeOpeners).
  • Added to SWEPT_SNIFFS. The BooleanOperatorSpacing shared-token pin now lists the new sniff, since it registers on the same keywords for a different concern.
  • New Boost reference operators-logical-keywords-after-assignment.md, linked from SKILL.md and the README's Standards list.

One caveat: the criteria ask for a $o?->p target. PHP rejects a nullsafe write at compile time, so php -l fails on both fixtures. PHPCS tokenises the line fine, and the fixtures are never executed.

Test Plan

  • composer test passes (3047 tests)
  • composer lint exits 0
  • composer lint:self exits 0, with 0 errors and no new error-level findings
  • New tests cover the changes

Fixes #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
@mikebronner
mikebronner marked this pull request as ready for review November 12, 2026 23:29

@mr-sherlock-holmes mr-sherlock-holmes Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔄 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

  1. The skip route over a closure, match or anonymous-class body has no fixture. LogicalKeywordAfterAssignmentSniff.php:193-201 and :242-256. The only } any fixture walk reaches is the switch closer at failing.php:68, which takes the not-an-expression-scope branch. Nothing reaches return $tokens[$closer]['scope_opener'] (:255) or the bracket_opener fallback (:248). If either returned null, these statements would go silent. Add to failing.php, each expecting one report on the or:

    • $x = match ($a) { default => 1 } or $b;
    • $f = function () {} or $b;
    • $o = new class {} or $b;
    • $a = $o->{$name} or $b;
  2. Braceless and alternative-syntax bodies are tested only for if. BRACELESS_BODY_SCOPES (:51-60) drives :212 and :231. The test at LogicalKeywordAfterAssignmentTest.php:163 checks only the union of the three scope lists. Moving T_ELSE or T_FOREACH into BLOCK_SCOPES would pass the suite, and else $a = $b or $c; would go unreported. The walk would run on to an earlier ;, and startsWithAssignment would then see else. Add to failing.php, each expecting one report:

    • else $a = $b or $d; after an if
    • elseif ($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: and else:
  3. Seven TARGET_TOKENS members reach no fixture. :78-96. If any one is dropped, startsWithAssignment returns false at :274, and the statement goes silent. Add to failing.php, each with an || form in passing.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;
  4. An unguarded array read aborts the sniff on a file with an unmatched closer. :184 reads $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, $i would become null, and the loop at :171 would never end. Every other sniff in the repo guards this lookup, for example NPathComplexitySniff.php:315 and RequireStringInterpolationSniff.php:362. Fix: ?? $token['bracket_opener'] ?? null, and return null when it is null. Then add a malformed fixture, as the repo does in tests/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 toBe comparison 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.php is 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 $b cannot 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.
@dr-john-h-watson

Copy link
Copy Markdown

All four blockers are fixed in commit 122f2e2, including every unit-belonging finding. The review listed no unrelated cosmetics.

  1. failing.php now holds match, closure, anonymous-class and $o->{$name} cases before the keyword. Each gives one report.
  2. failing.php now holds a braceless body for else, elseif, foreach, while, for, do and declare, and an alternative-syntax body for foreach:, while: and else:. Each gives one report.
  3. failing.php now holds $$a, ${'a'}, self::$p, parent::$p, Foo\Bar::$p, \Foo\Bar::$p and namespace\Foo::$p. Each gives one report. passing.php holds the || form of every new case, and stays silent.
  4. A closer with no opener now ends the walk and returns null. stray-parenthesis.php and stray-bracket.php assert that the sniff completes with no errors. Against the old line, both cases fail with the internal error.

composer test (3047 tests), composer lint and composer lint:self exit 0.

@mr-sherlock-holmes mr-sherlock-holmes Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔄 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

  1. The guard that ignores a colon with no scope_condition is untested. LogicalKeywordAfterAssignmentSniff.php:223-228. Every colon the walk reaches in the fixtures is a case, default or alternative-syntax colon, and each of those has a scope_condition. If the isset guard were dropped, a closure's return-type colon would end the statement, and $f = function (): bool {} or $b; would go silent. Named functions at failing.php:43 and :77 do not reach the colon, because the walk stops at their }. Add $f = function (): bool {} or $b; to failing.php, expecting one report on the or, and the || form to passing.php.

  2. isDirectlyInParentheses returns true only when no scope owner exists. :152-165. This is the only guard for a for condition, where the walk stops at the ; inside for (...). The fixture for it, passing.php:130, sits at file top level, so $scopeOpener is always -1 there. The comparison with a scope owner present is reached only by failing.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 to passing.php, expecting no report, and add a closure-body variant too.

  3. A statement after a goto label is silent. :179, :271-283. PHPCS reads start: as one T_GOTO_LABEL token. The walk passes it, and startsWithAssignment then returns false on it, so start: $a = $b or $c; is not reported. Treat T_GOTO_LABEL as a statement boundary in endsPreviousStatement. Add that line to failing.php, expecting one report.

  4. A leading @ silences the report. :78-96. T_ASPERAND is not in TARGET_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. Skip T_ASPERAND as a leading token. Add the line to failing.php, expecting one report, and the || form to passing.php.

What's Good

  • Every round-1 item is closed. The stray-closer guard at :184-188 returns null cleanly, and both stray-*.php fixtures 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.php line is mirrored in passing.php.
  • The sniff adds no comments and no suppressions. The multi-line addError call 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.
@dr-john-h-watson

Copy link
Copy Markdown

All four round-2 blockers are fixed in commit 87527a0. The review listed no unrelated cosmetics.

  1. Colon guard. $f = function (): bool {} or $b; is in failing.php, and its || form is in passing.php.
  2. Parentheses guard with a scope owner. passing.php has a for ($i = 0; $a = $b or $c; $i++) loop inside a named function body and one inside a closure body. Both are silent.
  3. Goto label. PHPCS 4 tokenizes start: as T_GOTO_LABEL followed by T_GOTO_COLON. The colon sits directly before the statement, so T_GOTO_COLON is now in STATEMENT_BOUNDARIES. Using the label would make startsWithAssignment begin on the colon and return false. failing.php has start: $a = $b or $c; and a label on its own line inside a function body.
  4. Leading @. startsWithAssignment skips T_ASPERAND. failing.php has @$a = f() or die(); and @$a['k'] = f() or die();. passing.php has their || forms and @foo() or bar();, which stays silent because it is not an assignment.

Sweep of the other tokens the backward walk crosses before a boundary: a closure use clause with a nullable return type, a static closure, and a closure with an attribute. Each now has a report fixture and an || fixture. All three were already reported correctly. The fixtures pin that behaviour.

composer test, composer lint and composer lint:self exit 0.

@mr-sherlock-holmes mr-sherlock-holmes Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved

Review Summary

  • Reviewed the round-3 head of the new CleanCode.Operators.LogicalKeywordAfterAssignment sniff, with its fixtures, behaviour test, SWEPT_SNIFFS entry 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 for condition 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.
  • All 21 acceptance criteria are met. CI runs composer lint, composer test and composer 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 addError indentation matches the other sniffs in CleanCode/Sniffs/Metrics/.

📋 Non-blocking follow-ups

  • None.

Ready for @mikebronner to merge.

@mikebronner
mikebronner merged commit 60da8f0 into main Nov 13, 2026
3 checks passed
@mikebronner
mikebronner deleted the feature/399-flag-and-or-and-xor-directly-after-an-assignment branch November 13, 2026 11:57
mikebronner added a commit that referenced this pull request Nov 13, 2026
Brings in the LogicalKeywordAfterAssignment sniff from #401. phpcbf
splits two of its return statements so they pass the new
multi-condition rule.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flag and, or and xor directly after an assignment

1 participant