Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
My understanding is that short, in-line, anonymous functions are permissible under Drupal's coding standards. An example of this is lines 220-221 from migrate/src/Tests/MigrateTestBase.php:
/** @var \Drupal\migrate\Entity\MigrationInterface $migration */
$destination = array_map(function() { return NULL; }, $migration->getDestinationPlugin()->getIds());
This code results in the following sniff result, each of which in this case I think is a false positive sniff:
FILE: ...Webs\tcm-dru8\core\modules\migrate\src\Tests\MigrateTestBase.php
----------------------------------------------------------------------
FOUND 4 ERRORS AFFECTING 1 LINE
----------------------------------------------------------------------
221 | ERROR | [x] Opening brace must be the last content on the line
| | (Generic.Functions.OpeningFunctionBraceKernighanRitchie.ContentAfterBrace)
221 | ERROR | [x] There should be no white space after an opening
| | "{"
| | (Drupal.WhiteSpace.OpenBracketSpacing.OpeningWhitespace)
221 | ERROR | [x] There should be no white space before a closing
| | "}"
| | (Drupal.WhiteSpace.CloseBracketSpacing.ClosingWhitespace)
221 | ERROR | [x] Closing brace must be on a line by itself
| | (Drupal.WhiteSpace.ScopeClosingBrace.Line)
----------------------------------------------------------------------
PHPCBF CAN FIX THE 4 MARKED SNIFF VIOLATIONS AUTOMATICALLY
Comments
Comment #2
Lars Toomre CreditAttribution: Lars Toomre as a volunteer commentedThe standards issue in which these false sniffs were encounter is #2624914: Fixes to migrate/src/Tests/*.php files.
Comment #3
klausiI think that anonymous functions should follow the same formatting as other function definitions https://www.drupal.org/coding-standards#functdecl
The coding standards do not mention anonymous functions at all, so not sure how we should deal with that.
Comment #4
klausiWe have now brief coding standards for anonymous functions: https://www.drupal.org/docs/develop/standards/coding-standards#functdecl
The examples there suggest to use multiple lines for anonymous functions, so I think this works as designed.