PHP_CodeSniffer icon indicating copy to clipboard operation
PHP_CodeSniffer copied to clipboard

false positive on Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed and compact

Open tebulrich opened this issue 3 years ago • 5 comments

Describe the bug Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed is triggered when variables are used via compact in function

Code sample

public static function insertMessage(int $id, string $language, string $translation): void
{
   Yii::$app->db->createCommand()->insert(
      'message',
      compact('id', 'language', 'translation')
   )->execute();
}

tebulrich avatar Jan 12 '23 12:01 tebulrich

Just seeing this as well. My code sample:

function get_transient_key( string $content, array $attributes, bool $is_feed, array $auto_detect_languages ): ?string {
	$hash_input = wp_json_encode(
		array_merge(
			compact( 'content', 'attributes', 'is_feed', 'auto_detect_languages' ),
			[
				'version' => PLUGIN_VERSION,
			]
		)
	);
	if ( ! is_string( $hash_input ) ) {
		return null;
	}
	return 'shcb-' . md5( $hash_input );
}

westonruter avatar Oct 27 '23 19:10 westonruter

I concur this is a bug, but one which may not be that easy to fix.

To be honest, in my personal opinion, the use of compact() is a bit outdated and I'm actually surprised that PHP hasn't deprecated the function yet.

Out of curiousity: why not just declare the array ?

To take @westonruter's code sample, this could be rewritten to:

	$hash_input = wp_json_encode(
		array(
			'content' => $content,
			'attributes' => $attributes,
			'is_feed' => $is_feed,
			'auto_detect_languages' => $auto_detect_languages,
			'version' => PLUGIN_VERSION,
		)
	);

This is also a micro-optimization as it gets rid of two unnecessary function calls.

jrfnl avatar Oct 27 '23 19:10 jrfnl

I guess because it's less redundant. JavaScript supports this same syntax as part of the language, for example if the above were written in JS instead:

const hash_input = JSON.stringify(
    {
        content, 
        attributes, 
        is_feed, 
        auto_detect_languages,
        version: PLUGIN_VERSION
    }
);

Granted this is PHP and not JS.

westonruter avatar Oct 27 '23 20:10 westonruter

Granted this is PHP and not JS.

Exactly.

jrfnl avatar Oct 27 '23 20:10 jrfnl

In my case, i was working with a legacy app, where I had to live with compact (only had to use it for this one project and didnt like it at all, but thats another thing)

tebulrich avatar Oct 27 '23 20:10 tebulrich