Skip to content
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

Rule: Opening and closing braces must be within the same <?php ... ?> block #41

Open
schmengler opened this issue Jun 4, 2018 · 0 comments
Labels
accepted This rule is accepted by extdn

Comments

@schmengler
Copy link
Collaborator

Rule

The following should be discouraged:

<?php if ($block->hasThings()) { ?>
<div>
  <h1>Things</h1>
  <?php foreach ($block->getThings() as $thing) { ?>
  <h2><?= $block->escapeHtml($thing->name()) ?></h2>
  <div>
    <div>Bunch of HTML</div>
  </div>
  <?php } ?>
</div>
<?php } ?>

Instead, use alternative control structure syntax, i.e. endif, endforeach etc., if HTML is embedded within the block:

<?php if ($block->hasThings()): ?>
<div>
  <h1>Things</h1>
  <?php foreach ($block->getThings() as $thing): ?>
  <h2><?= $block->escapeHtml($thing->name()) ?></h2>
  <div>
    <div>Bunch of HTML</div>
  </div>
  <?php endforeach ?>
</div>
<?php endif ?>

Reason

A mix of HTML and PHP in templates with different indentations is already hard to read. Lonely closing braces make it even harder to reasonate about the code, and easier to introduce bugs. With the alternative control structure syntax, it becomes a bit clearer, which block becomes closed, improving readability and maintainability.

We do not want to disallow the normal PHP syntax altogether in templates, because as long as it is within one PHP block, it not harder to read and has the advantage of familiarity:

<?php
if ($block->hasThings()) {
  $headline = 'A bucket of things';
} else {
  $headline = 'An empty bucket';
}

is not worse than

<?php
if ($block->hasThings()):
  $headline = 'A bucket of things';
else:
  $headline = 'An empty bucket';
endif;

and certainly better than

<?php if ($block->hasThings()): ?>
<?php   $headline = 'A bucket of things'; ?>
<?php else: ?>
<?php   $headline = 'An empty bucket'; ?>
<?php endif; ?>

Previous discussion: #16

Implementation

Trace opening and closing braces as well as opening and closing <?php tags, alert if there is a mismatch

@schmengler schmengler added the accepted This rule is accepted by extdn label Jun 4, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
accepted This rule is accepted by extdn
Projects
None yet
Development

No branches or pull requests

1 participant