Skip to content

Fix lost file comment when it precedes declare(strict_types=1)#182

Open
xHeaven wants to merge 1 commit intonette:masterfrom
xHeaven:extractor
Open

Fix lost file comment when it precedes declare(strict_types=1)#182
xHeaven wants to merge 1 commit intonette:masterfrom
xHeaven:extractor

Conversation

@xHeaven
Copy link
Contributor

@xHeaven xHeaven commented Mar 3, 2026

Extractor::extractAll() fails to extract the file-level doc comment when it appears before declare(strict_types=1). This means PhpFile::fromCode() silently drops the comment during a print-then-reparse round-trip.

We discovered it in tempest/framework where our generation package round-trips through fromCode().

The PsrPrinter (and Printer) places the file comment before the declare statement:

<?php

/**
 * This file has been generated.
 */

declare(strict_types=1);

namespace App;

But extractAll() (changed here) skips the Declare_ node and only checks the next statement for a doc comment. Since the PHP parser attaches the comment to the Declare_ node it precedes, the comment is never found.

The added tests in the above commit also only cover cases where the comment comes after a singleline declare, not before it.

Quick reproduction:

$file = new PhpFile();
$file->setStrictTypes();
$file->setComment('Generated file.');
$file->addNamespace('App')->addClass('Foo');

$code = (new PsrPrinter())->printFile($file);
$roundTripped = PhpFile::fromCode($code);

$roundTripped->getComment(); // null, expected 'Generated file.'

I've added a regression test as well to cover this case.

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

Successfully merging this pull request may close these issues.

1 participant