PHP_CodeSniffer icon indicating copy to clipboard operation
PHP_CodeSniffer copied to clipboard

Way to allow empty methods to have braces on the same line (useful for PHP 8 property promotion)

Open simPod opened this issue 3 years ago • 6 comments

I have sniffs enabled to ensure that function braces are on the separate lines si this style is enforced:

public function __construct(A $a)
{
    $this->a = $a;
}

and this is not allowed

public function __construct(A $a) {
    $this->a = $a;
}

However, e.g. for property promotion it would be useful to have a way to allow this as it saves 2 lines:

public function __construct(private A $a) {}

Though I don't see a way to configure it while enforcing the style mentioned above for non empty functions:

Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine: Opening brace should be on a new line
Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore: Closing brace must be on a line by itself

simPod avatar Apr 06 '21 09:04 simPod

There is no option for this in PHPCS as none of the sniffs change their rules specifically for constructor property promotion. A new feature would need to be added for this.

See also #3278

gsherwood avatar Apr 06 '21 22:04 gsherwood

I see, #3278 is pretty same.

simPod avatar Apr 06 '21 22:04 simPod

For now I'm using this approach, but it would be nice if it could be configured in phpcs.xml.dist specific rule or disabled just for that function, using @phpcs:disable.

/**
 * CheckUserLoginService constructor
 *
 * @phpcs:disable Squiz.WhiteSpace.ScopeClosingBrace
 * @param CompanyRepository $companyRepository
 * @param ColorService $colorService
 */
public function __construct(
    protected CompanyRepository $companyRepository,
    protected ColorService $colorService
) {}

/**
 * @phpcs:enable Squiz.WhiteSpace.ScopeClosingBrace
 * @param Type $var
 */
public function FunctionName(Type $var = null)
{} // <--- Error here. OK 👍

thiagobraga avatar Apr 18 '21 17:04 thiagobraga

public function __construct(
    protected CompanyRepository $companyRepository,
    protected ColorService $colorService
    // phpcs:ignore Squiz.WhiteSpace.ScopeClosingBrace
) {}

simPod avatar Apr 18 '21 17:04 simPod

Hi, is there any other development regarding this error?

paveljanda avatar Mar 29 '22 13:03 paveljanda