WordPress-Coding-Standards
WordPress-Coding-Standards copied to clipboard
Issues with closures and `use` as arguments
I'm having issues when I feed closures that use
local variables into function calls, for example, add_action()
.
Example test.php
file:
<?php
$foo = 'foo';
$bar = 'bar';
add_action( function () use (
$foo,
$bar
) {
return "{$foo}{$bar}";
} );
Run:
phpcs test.php --standard=WordPress --sniffs=PEAR.Functions.FunctionCallSignature
Output:
-----------------------------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
-----------------------------------------------------------------------------------------------------
7 | ERROR | [x] Multi-line function call not indented correctly; expected 4 spaces but found 0
-----------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
-----------------------------------------------------------------------------------------------------
This is also true when passing the closure as argument to a mehod, of course:
$foo->inject( function () use (
$foo,
$bar
) { ... } );
Am I doing something wrong? What would be the WPCS-conform way of formatting this? I'm pretty sure it is not the following, which happens to be what PHPCS is fine with:
<?php
$foo = 'foo';
$bar = 'bar';
add_action( function () use (
$foo,
$bar
) {
return "{$foo}{$bar}";
} );
Hi @tfrommen, I'm going to have to take a look at the PEAR sniff to see if it can actually deal with closures with use statements. If not, we may need to patch the upstream sniff.
Your issue is loosely related to #1071 in which we have been discussing creating dedicated sniffs for checking the formatting of use
statements, though by the looks of your issue, the current proposal would definitely conflict with the PEAR sniff as it is now.