PHPCSStandards / PHP_CodeSniffer

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
BSD 3-Clause "New" or "Revised" License
880 stars 54 forks source link

DisallowMultipleAssignments false positive when assigning to variable property of an object in an array #598

Open GaryJones opened 4 weeks ago

GaryJones commented 4 weeks ago

Describe the bug

False positive on a complex statement that suggests the assignment is not the first block of code.

Try assigning a value to a property of an object contained in an (indexed) array.

Code sample

<?php

$filtered_results[ $i ]->$field = $result;

Custom ruleset

Can be reproduced with the WordPress-Extra or Squiz rulesets, or any combination using the Squiz.PHP.DisallowMultipleAssignments rule.

To reproduce

Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above...
  2. Run phpcs test.php --standard=Squiz --sniffs=Squiz.PHP.DisallowMultipleAssignments -s or similar
  3. See error message displayed
    3 | ERROR | Assignments must be the first block of code on a line (Squiz.PHP.DisallowMultipleAssignments.Found)

Expected behavior

No violation reported.

Versions (please complete the following information)

Operating System MacOS 14.6.1
PHP version 7.4
PHP_CodeSniffer version 3.9.2
Standard Squiz
Install type Composer

Additional context

None of the tests seem to have an assignment to a property of an object in an array.

Please confirm

jrfnl commented 4 weeks ago

@GaryJones Thanks for reporting this. I can confirm the issue, which appears to be caused by the variable variable, i.e. the variable for the property name:

$filtered_results[] = $result;
$filtered_results[ $i ] = $result;

$filtered_results->field = $result;
$filtered_results->$field = $result;

$filtered_results[ $i ]->field = $result;
$filtered_results[ $i ]->$field = $result; // <- This is the bug, all other test cases in this code sample are handled correctly.
jrfnl commented 5 days ago

@GaryJones PR #610 should fix this. Testing appreciated.