prettier / prettier/plugin-php

Prettier inserts a syntax error when there is a comment after an if statement

Open
#2,494 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
1.9k
Forks
139
PR merge metrics
No merged PRs in 30d

Description

When prettier is used via command line or via VSCode shortcut, prettier inserts an extra <?php string, creating a syntax error.

Input:

<?php if (true): // example comment
  ?>
  <h1>Heading</h1>
<?php endif; ?>

Output:

<?php if (true):<?php
  // example comment
  ?>
  <h1>Heading</h1>
<?php endif; ?>

This behavior, however, is not present within the reporting tool, where the output is as expected: @prettier/plugin-php v0.25.0
Playground link

The .prettierrc file:

{
  "useTabs": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "semi": true,
  "singleQuote": true,
  "arrowParens": "avoid",
  "printWidth": 120,
  "plugins": ["@prettier/plugin-php"]
}
  • Prettier version: 3.8.3
  • PHP Plugin version: 0.25.0
Further information

This issue only happens when a comment is right after an if statement, and the comment is the last thing inside the php block. Here are examples of cases where the code is formatted correctly:

<?php
// example comment
if (true): ?>
  <h1>Heading</h1>
<?php endif; ?>
<?php
$test = 'Foo';
if (true):
  // example comment
  $test = 'Bar'; ?>
  <h1>Heading</h1>
<?php
endif; ?>

Those examples are after they were formatted using the command line prettier.

The second example is somewhat questionable, as I suspect the endif statement should not be moved to a new line - before the formatting happened it was in a single line, like in the first example.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal PHP reproduction from the issue using the command-line formatter, then compare its output with the reporting tool or playground. Trace the PHP block and trailing-comment formatting path responsible for inserting the extra opening tag. Done means the comment-after-if case formats without an extra <?php and remains syntactically valid.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.