Skip to content

Commit

Permalink
Add custom sniff to warn about empty()
Browse files Browse the repository at this point in the history
Signed-off-by: Shyamsundar Gadde <[email protected]>
  • Loading branch information
ShyamGadde committed Jan 9, 2025
1 parent b6e5c5a commit f9eb45e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
40 changes: 40 additions & 0 deletions tools/phpcs/Sniffs/PHP/RestrictedEmptyConstructSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* Sniff to restrict usage of the empty() construct.
*
* @package performance
*/

namespace WPPCS\WPP\Sniffs\PHP;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;

// phpcs:ignoreFile WordPress.NamingConventions.ValidVariableName -- required by the interface.

/**
* Restricts usage of empty().
*/
class RestrictedEmptyConstructSniff implements Sniff {

/**
* Registers the tokens that this sniff wants to listen for.
*/
public function register(): array {
return array( \T_EMPTY );
}

/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the stack.
*/
public function process( File $phpcsFile, $stackPtr ): void { // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint -- required by the interface.
$phpcsFile->addWarning(
'Usage of empty() can mask code problems. Consider explicit checks instead.',
$stackPtr,
'EmptyConstructUsage'
);
}
}
8 changes: 8 additions & 0 deletions tools/phpcs/phpcs.ruleset.xml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,14 @@
<exclude name="SlevomatCodingStandard.TypeHints.PropertyTypeHint.MissingTraversableTypeHintSpecification" /><!-- TODO: Investigate this -->
</rule>

<!-- Do no apply for custom sniffs. -->
<rule ref="WordPress.Files.FileName.NotHyphenatedLowercase">
<exclude-pattern>./Sniffs/*</exclude-pattern>
</rule>
<rule ref="WordPress.Files.FileName.InvalidClassFileName">
<exclude-pattern>./Sniffs/*</exclude-pattern>
</rule>

<!-- Exclude built plugins and built assets in plugins. -->
<exclude-pattern>./build/*</exclude-pattern>

Expand Down

0 comments on commit f9eb45e

Please sign in to comment.