PHPCSStandards / PHPCSExtra

A collection of code standards for use with PHP_CodeSniffer
GNU Lesser General Public License v3.0
90 stars 8 forks source link

Add Sniff to ensure file only uses PHP native functions or functions defined in the current file #315

Open aaronjorbin opened 4 weeks ago

aaronjorbin commented 4 weeks ago

Is your feature request related to a problem?

In WordPress, there are a handful of files that need to function on their own. A sniff that detects the use of functions besides those available from PHP itself and those declared in the file itself.

Describe the solution you'd like

File 1 which would pass without issue:


<?PHP 

function foo( $arg ){
 $arguments = func_get_args(); // allowed since function is a part of the PHP standard lib
}

function bar( $arg ){
 return foo( $arg ); // allowed since foo is defined in this file
}

File 2 which would raise an issue


<?PHP

function baz( $arg ){
  return foo( $arg ); // foo is defined in a different file and these this would trigger an issue
}

?>

Additional context (optional)

This is discussed in https://core.trac.wordpress.org/ticket/61694 which is a follow up to prevent issues like the one described in https://core.trac.wordpress.org/ticket/61680

jrfnl commented 4 weeks ago

Notes which I previously already shared about this feature request:

Would be quite doable to write in principle, but will never do exactly what you want - get_defined_functions()['internal'] (which such a sniff would use to determine the PHP native functions) will get you all the functions defined at runtime of the sniff and has no information on whether the function is defined in the PHP standard/Core library, in a bundled, always-on PHP extension or in an optional or even a PECL extension which happens to be enabled in the runtime running the sniff/script.

I have a utility lined up for PHPCSUtils 1.2.0 which will make writing the sniff straight-forward (and reliable).

Source: https://core.trac.wordpress.org/ticket/61694#comment:8

Regarding PHPCSUtils 1.2.0:

The specific utility in PHPCSUtils 1.2.0 which I'm talking about is a namespace aware DeclaredFunctionsTracker, which will be able to get the fully qualified name of all declared functions in a file.

Additionally, PHPCSUtils 1.2.0 is expected to include a NamespaceTracker and an ImportUseTracker, which will allow to resolve function calls to their fully qualified name, meaning that it will make the sniff more reliable.

Mind: it will still take a while before PHPCSUtils 1.2.0 is released (I'm currently still finishing off the 1.1.0 release).

Other caveats/Open questions