Skip to content

Is it within PSR-12 standard to break foreach into multiple lines #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
snake-py opened this issue Sep 23, 2022 · 4 comments
Closed

Is it within PSR-12 standard to break foreach into multiple lines #49

snake-py opened this issue Sep 23, 2022 · 4 comments

Comments

@snake-py
Copy link

snake-py commented Sep 23, 2022

The foreach is not too clear whether it is okay to break the expression into multiple lines. https://www.php-fig.org/psr/psr-12/#55-foreach . Other expressions like for and while are very clear on the issue. I am unsure why this restriction is on foreach if other loop expressions are "allowed" to do this.

I need to know for these two issues:
squizlabs/PHP_CodeSniffer#3673
prettier/plugin-php#2060

example:

foreach (
    $client->getContractsByCustomerId($customer["id"])
    as $contract
) {

or is only this within the standard:

foreach ($client->getContractsByCustomerId($customer["id"]) as $contract) {
@KorvinSzanto
Copy link
Contributor

KorvinSzanto commented Sep 26, 2022

Nether PSR-12 nor the Coding Style PER would allow splitting foreaches the way you're showing, the only allowed use of foreach is as shown in the example you linked. A more readable approach would be to use a variable to store the array you're iterating over:

$contracts = $client->getContractsByCustomerId($customer['id']);
foreach ($contracts as $contract) {
    ...
}

@cseufert
Copy link

@KorvinSzanto I don't see anywhere that this is explicitly prohibited, or allowed within the PER-CS or PSR-12 language around the foreach expressions, it is explicitly allowed for while, if, for, etc, will this be clarified in a future edition of PER-CS?

@KorvinSzanto
Copy link
Contributor

I'd definitely accept a pull request, it could be written more clearly with MUSTs.

@cseufert
Copy link

@KorvinSzanto As a contributor and user of the PHP prettier code formatter, I am trying to understand where the decision that a foreach must be on a single line, while there is no such restriction on almost all other control structure's expressions. I would prefer to open a PR to document a 'standard' way to split a foreach expression onto multiple lines where there is not enough room for it all to fit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants