fix: place PHPDoc before class attributes when writing to models (#1765)

When using --write/-W with models that have PHP 8 attributes (e.g.
#[ObservedBy(...)]), the generated PHPDoc block was inserted between
the attribute and the class declaration:

    #[ObservedBy([ImageObserver::class])]
    /**
     * @property string $name
     */
    final class Image extends Model

This breaks PHPStan/Larastan because the docblock must come before
the attributes. The fix scans backward from the class declaration to
find any preceding PHP 8 attributes and inserts the docblock before
them:

    /**
     * @property string $name
     */
    #[ObservedBy([ImageObserver::class])]
    final class Image extends Model

Fixes #1734
This commit is contained in:
isaackaara
2026-03-04 10:52:03 +01:00
committed by GitHub
parent 3d8fccd700
commit 392d5cfc80
+8
View File
@@ -1202,6 +1202,14 @@ class ModelsCommand extends Command
$replace = "{$modelDocComment}\n";
$pos = strpos($contents, "final class {$classname}") ?: strpos($contents, "class {$classname}");
if ($pos !== false) {
// If PHP 8 attributes (e.g. #[ObservedBy(...)]) precede the class
// declaration, insert the docblock before the first attribute so that
// the resulting order is: docblock → attributes → class.
$before = substr($contents, 0, $pos);
if (preg_match('/(\s*(?:#\[.+?\]\s*)+)$/s', $before, $matches)) {
$pos -= strlen($matches[1]);
$replace = "{$modelDocComment}\n";
}
$contents = substr_replace($contents, $replace, $pos, 0);
}
}