WordPress-Coding-Standards icon indicating copy to clipboard operation
WordPress-Coding-Standards copied to clipboard

WP/AlternativeFunctions: remove invalid STDIN/STDOUT/STDERR resource handling

Open rodrigoprimo opened this issue 4 months ago • 3 comments

The WordPress.WP.AlternativeFunctions sniff suggests WP functions that should be used instead of native PHP functions. In the case of file_get_contents(), file_put_contents(), fopen(), and readfile(), this recommendation depends on the parameter values.

The sniff currently bows out when a resource is passed as the first parameter (STDIN, STDOUT, STDERR), but this is incorrect because these functions only accept string filenames, not resources. Code like fopen(STDIN, 'w') results in a fatal error: "Uncaught TypeError: fopen(): Argument #1 ($filename) must be of type string, resource given" (https://3v4l.org/vkbB4).

There are a few code examples, like the one above, in the sniff tests. They were introduced in #1655. Unless I'm missing something, I don't see a reason for the sniff to have special handling for invalid code. If that is indeed the case, this condition can be removed:

https://github.com/WordPress/WordPress-Coding-Standards/blob/f6965eed3db6393bfc89e975bcd3fb27186c74c2/WordPress/Sniffs/WP/AlternativeFunctionsSniff.php#L358

Removing the condition above means that the sniff will start triggering a warning for the code sample presented in this issue, which I believe is the correct behavior.

Initially discussed in https://github.com/WordPress/WordPress-Coding-Standards/pull/2581#discussion_r2330482665

rodrigoprimo avatar Sep 09 '25 17:09 rodrigoprimo

for the code sample presented in this issue

Which code sample is that ?

jrfnl avatar Sep 11 '25 17:09 jrfnl

Which code sample is that ?

fopen(STDIN, 'w')

rodrigoprimo avatar Sep 12 '25 15:09 rodrigoprimo

Okay, so @rodrigoprimo and me discussed this in a call.

I don't think the special handling should be removed. I do think the criteria for which the special handling is applied are incorrect (nicely found @rodrigoprimo !).

Think:

fwrite( STDOUT, $text );

I have a feeling the WP file system is not the correct alternative for a function call like that and we should not recommend for that function call to be changed.

In other words, I believe some research needs to be done which of the functions this sniff is listening for accept a resource parameter and for which that resource parameter could conceivably be STDIN/STDOUT/STDERR. Once that list becomes clear, those functions will need special casing to make an exception for STDIN/STDOUT/STDERR and the current special casing should probably be removed (or replaced).

Does that make sense ?

jrfnl avatar Sep 15 '25 15:09 jrfnl