PHP Code Sniffer Errors Explained

Messages output by PHP_CodeSniffer or “phpcs” are often confusing, especially when using an opinionated coding standard like the WordPress Coding Standard. Below, some of these messages are described in detail.

SQL wildcards for a LIKE query should be passed in through a replacement parameter

Instead of writing a query like this:

	$column_name = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT		COLUMN_NAME
			
			FROM		INFORMATION_SCHEMA.COLUMNS

			WHERE		TABLE_NAME = %s
						AND TABLE_SCHEMA = %s
						AND EXTRA LIKE '%auto_increment%'",
			$prefixed_table_name,
			DB_NAME
		)
	);

Move the ‘%auto_increment’ string literal to a parameter like this:

	$column_name = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT		COLUMN_NAME
			
			FROM		INFORMATION_SCHEMA.COLUMNS

			WHERE		TABLE_NAME = %s
						AND TABLE_SCHEMA = %s
						AND EXTRA LIKE %s",
			$prefixed_table_name,
			DB_NAME,
			'%auto_increment%'
		)
	);

The var keyword must not be used to declare a property

Delete the var keyword. Before: protected var $rendered_form_ids; After: protected $rendered_form_ids;

End of line character is invalid; expected “\n” but found “\r\n”

Convert the line endings in the file from Windows to *nix. In Visual Studio Code, look for the line ending indicator in the status bar at the bottom. If you see CRLF, change it to LF.

The phpcs report contains invalid json. Please review “Diagnosing Common Errors” in the plugin README

Can you run phpcs –standard=WordPress . in the project directory without errors? If you get this error:

Fatal error: Uncaught TypeError: vsprintf(): Argument #2 ($values) must be of type array, string given in /Users/Ore/.composer/vendor/squizlabs/php_codesniffer/src/Files/File.php:1056

…this fix worked for me: https://wordpress.stackexchange.com/a/385848/13090

It’s a PHP 8 problem. Try the above solution if you’re having problems on PHP 8.

Make sure the report output is valid JSON for the file you’re trying to sniff. phpcs includes/file.php --report=json should output valid JSON. If you need a tool to verify the JSON, try jsonlint.com. If the JSON is valid, restart VS Code (or whatever editor you’re using), make a superficial change to the file and save it.

If the JSON is not valid, read the extra output and fix whatever that problem is. It could be a PHP error or a warning about a PHP extension like Xdebug.