Skip to content

[FR] Arrow functions: sniff to enforce spacing after the fn keyword #441

Description

@rodrigoprimo

Setting the scene

PHP 7.4 introduced arrow functions (short closures) via the fn() => expression syntax. At this moment, neither PHPCS itself nor PHPCSExtra contain a sniff to handle the spacing after the fn keyword.

The PER Coding Standard from FIG, since PER 2.0, outlines a set of rules for short closures in section 7.1.

Proposed new sniff: Universal.WhiteSpace.FnKeywordSpacing

To address this rule from PER:

The fn keyword MUST NOT be succeeded by a space.

Notes for the implementation

The fn keyword is tokenized as T_FN, so registering [T_FN] is a good entry point. The SpacesFixer from PHPCSUtils handles the check for the spacing after the keyword.

Suggested error code:

  • SpacingAfterKeyword: incorrect spacing after the fn keyword.

The sniff should be configurable and use the PER-CS value as default:

  • public $spacingAfterKeyword = 0;

Describe the solution you'd like

A new sniff as outlined above.

The sniff should be able to flag and auto-fix the following:

// OK.
$fn = fn($x) => $x + 1;

// Error: space after the `fn` keyword.
$fn = fn ($x) => $x + 1;

Also see the examples outlined in the PER documents (rules + migration guide).

Additional context (optional)

This ticket is part of a series of tickets that is the result of a detailed analysis of the rules as outlined in PER-CS 2.0, as well as a critical look at what's still missing rule-wise.

  • I intend to create a pull request to implement this feature.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions