Skip to content

docs(types): PHPDoc generics for relations, scopes, collections and builders (#44, lot A, 2/2) - #46

Open
ogorzalka wants to merge 2 commits into
mainfrom
chore/phpstan-level6-generics
Open

ogorzalka wants to merge 2 commits into
mainfrom
chore/phpstan-level6-generics

Conversation

@ogorzalka

@ogorzalka ogorzalka commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Part of #44, lot A, second of two: generics, in PHPDoc only. Merge the first PR (array value types) before this one: this branch contains its commit. Apart from comments, the only line this PR adds to src is one use import.

The analysed level stays at 5. phpstan.neon, phpstan-baseline.neon, .harness.json and api-surface.json are untouched. Level 6 cannot be reached without regenerating the baseline (see below).

PHPStan error counts

PHPStan run main first PR this PR
level 6, with the current baseline 155 88 23
level 6, without the baseline 203 136 71
level 7, without the baseline 215 82
level max, without the baseline 315 162

What changes

  • Generics on the relations, on the return of Model::belongsTo() and belongsToMany(), class-string<T> on the $related argument of the four relation factories, and a template on setInstanceConnection().
  • Generics on query scope parameters, on MenuItem::newCollection() and on the sibling collections.
  • CommentBuilder, PostBuilder and TaxonomyBuilder declare @template TModel of X = X and @extends Builder<TModel>. The default keeps a bare PostBuilder valid.
  • MetaFields::$builtInClasses and getMetaClass() now say the classes are class-string<Meta>.

Effect on user projects (static analysis only, reproduced)

A subclass that overrides a typed relation with another related class is now reported, even at level 5. A fixture with Book extends Post whose author() returns belongsTo(Author::class, ...), Author extends User, gives after this PR (nothing before):

Method Consumer\Book::author() should return BelongsTo<Pollora\Colt\Model\User, $this(Consumer\Book)>
but returns BelongsTo<Consumer\Author, $this(Consumer\Book)>.

(namespaces of BelongsTo shortened). Eloquent's related model template is invariant, so this is the usual consequence of typing relations. covariant would avoid it but would stop associate() and similar calls from type checking. Runtime behaviour is unaffected. Please decide whether that is acceptable in a minor release. The same applies in principle to a subclass that redeclares $builtInClasses with a wider PHPDoc type.

What this proves

  • With the baseline removed, the level 5 run gives the same 48 errors as main (files, identifiers, messages).
  • composer qa:fast: every gate passed. composer qa: exit 0, every gate that ran passed (280 tests passed, 1 incomplete). Rector dry run: nothing to change.
  • On a throwaway copy with Laravel 12.75.0: PHPStan with the repository configuration reports no error, level 6 reports the same 23 (13 generics, 10 iterable values), and the 280 tests pass.
  • pollora/framework (main, 64acf70), whose models extend Colt's: its PHPStan run, with its own configuration, gives the same output with Colt from main, from the first PR and from this one (a single deprecation notice in all three, unrelated, seen on local PHP 8.5). The CI downstream job only runs the framework's unit tests.
  • CI on 6abb148: every check passes (the harness WordPress matrix job is skipped), including the quality gates with Semgrep, backward compatibility (QA-05) and the framework unit tests downstream.

What it does not prove

  • Relations built on hasMany() / hasOne() (fields, meta, replies, comments, children, Taxonomy::meta, Term::taxonomy, User::posts, User::comments) are declared, but PHPStan cannot check them while those two factories return a raw type. In a throwaway run with the factories templated, none of these declarations raised an error.
  • Semgrep is not installed locally, and the WordPress tests, coverage, mutation and backward compatibility checks were not run locally: they rest on CI, which runs mutation testing on changed files only.
  • No run with Larastan, and no real user project analysed.

The 23 errors left, and why

Each of these changes the text or the count of a baseline entry, which reportUnmatchedIgnoredErrors turns into a failure. Fixing them needs a regenerated baseline, which is a maintainer's decision.

Declarations Errors Baseline effect
$fillable (Post, Option, PostMeta, TermMeta, UserMeta, CommentMeta), User::$hidden 7 entries disappear
TermRelationship::$primaryKey 1 entry reworded, stays
ThumbnailMeta::size(), Post::getFormat() 2 entries disappear
scopeNewest() / scopeOldest() return, on Post and User 4 entries reworded
Model::hasMany(), hasOne() 2 reword the thumbnail, attachment, revision entries
Post::thumbnail(), attachment(), revision(), Menu::items() 4 entries reworded
Post::parent() 1 rewords the MenuItem::parent() entry
Post::taxonomies() 1 the Model::$term entry disappears, Term::$slug then occurs twice
Post::newCollection() 1 entry disappears

Commands for the maintainer

After both PRs are merged, from an up to date main:

git switch -c chore/phpstan-level6 origin/main
# save the patch below as level6.patch
git apply level6.patch
# edit phpstan.neon: level: 5 -> level: 6
vendor/bin/phpstan analyse --generate-baseline phpstan-baseline.neon
vendor/bin/pollora-qa ratchet --update
composer qa

Measured on a throwaway copy with the patch applied: level 6 without any baseline reports 37 errors, none of them missingType.* or argument.templateType, against 48 baselined occurrences today. The baseline generation and ratchet --update themselves were not run, nor were the tests with the patch applied. Review the regenerated file before committing it: Term::$slug goes from 1 to 2 occurrences. The patch also widens the user-facing effect described above to parent(), taxonomies() and the other relations it types.

level6.patch
--- a/src/Concerns/OrderScopes.php
+++ b/src/Concerns/OrderScopes.php
@@ -15,7 +15,7 @@
 {
     /**
      * @param  Builder<static>  $query
-     * @return Builder
+     * @return Builder<static>
      */
     public function scopeNewest(Builder $query)
     {
@@ -24,7 +24,7 @@
 
     /**
      * @param  Builder<static>  $query
-     * @return Builder
+     * @return Builder<static>
      */
     public function scopeOldest(Builder $query)
     {
--- a/src/Model.php
+++ b/src/Model.php
@@ -45,7 +45,7 @@
      * @param  class-string<TRelatedModel>  $related
      * @param  string  $foreignKey
      * @param  string  $localKey
-     * @return HasMany
+     * @return HasMany<TRelatedModel, $this>
      */
     public function hasMany($related, $foreignKey = null, $localKey = null)
     {
@@ -68,7 +68,7 @@
      * @param  class-string<TRelatedModel>  $related
      * @param  string  $foreignKey
      * @param  string  $localKey
-     * @return HasOne
+     * @return HasOne<TRelatedModel, $this>
      */
     public function hasOne($related, $foreignKey = null, $localKey = null)
     {
--- a/src/Model/Menu.php
+++ b/src/Model/Menu.php
@@ -25,7 +25,7 @@
     protected $with = ['term', 'items'];
 
     /**
-     * @return BelongsToMany
+     * @return BelongsToMany<MenuItem, $this>
      */
     public function items()
     {
--- a/src/Model/Meta/CommentMeta.php
+++ b/src/Model/Meta/CommentMeta.php
@@ -20,7 +20,7 @@
     protected $table = 'commentmeta';
 
     /**
-     * @var array
+     * @var array<int, string>
      */
     protected $fillable = ['meta_key', 'meta_value', 'comment_id'];
 
--- a/src/Model/Meta/PostMeta.php
+++ b/src/Model/Meta/PostMeta.php
@@ -20,7 +20,7 @@
     protected $table = 'postmeta';
 
     /**
-     * @var array
+     * @var array<int, string>
      */
     protected $fillable = ['meta_key', 'meta_value', 'post_id'];
 
--- a/src/Model/Meta/TermMeta.php
+++ b/src/Model/Meta/TermMeta.php
@@ -20,7 +20,7 @@
     /** @var string */
     protected $primaryKey = 'meta_id';
 
-    /** @var array */
+    /** @var array<int, string> */
     protected $fillable = ['meta_key', 'meta_value', 'term_id'];
 
     /**
--- a/src/Model/Meta/ThumbnailMeta.php
+++ b/src/Model/Meta/ThumbnailMeta.php
@@ -40,7 +40,7 @@
 
     /**
      * @param  string  $size
-     * @return array
+     * @return array<mixed>|string
      *
      * @throws \Exception
      */
--- a/src/Model/Meta/UserMeta.php
+++ b/src/Model/Meta/UserMeta.php
@@ -26,7 +26,7 @@
     protected $primaryKey = 'umeta_id';
 
     /**
-     * @var array
+     * @var array<int, string>
      */
     protected $fillable = ['meta_key', 'meta_value', 'user_id'];
 
--- a/src/Model/Option.php
+++ b/src/Model/Option.php
@@ -37,7 +37,7 @@
     protected $primaryKey = 'option_id';
 
     /**
-     * @var array
+     * @var array<int, string>
      */
     protected $fillable = [
         'option_name',
--- a/src/Model/Post.php
+++ b/src/Model/Post.php
@@ -75,7 +75,7 @@
     protected static $postTypes = [];
 
     /**
-     * @var array
+     * @var array<int, string>
      */
     protected $fillable = [
         'post_content',
@@ -184,6 +184,7 @@
      * appended attributes in bulk when it is serialised (no N+1 on toArray/toJson).
      *
      * @param  array<int, static>  $models
+     * @return PostCollection<int, static>
      */
     public function newCollection(array $models = []): PostCollection
     {
@@ -201,7 +202,7 @@
     }
 
     /**
-     * @return HasOne
+     * @return HasOne<ThumbnailMeta, $this>
      */
     public function thumbnail()
     {
@@ -210,7 +211,7 @@
     }
 
     /**
-     * @return BelongsToMany
+     * @return BelongsToMany<Taxonomy, $this>
      */
     public function taxonomies()
     {
@@ -239,7 +240,7 @@
     }
 
     /**
-     * @return BelongsTo
+     * @return BelongsTo<Post, $this>
      */
     public function parent()
     {
@@ -255,7 +256,7 @@
     }
 
     /**
-     * @return HasMany
+     * @return HasMany<Post, $this>
      */
     public function attachment()
     {
@@ -264,7 +265,7 @@
     }
 
     /**
-     * @return HasMany
+     * @return HasMany<Post, $this>
      */
     public function revision()
     {
@@ -400,7 +401,7 @@
     /**
      * Get the post format, like the WP get_post_format() function.
      *
-     * @return bool|string
+     * @return array<mixed>|string|false
      */
     public function getFormat(): string|array|false
     {
--- a/src/Model/TermRelationship.php
+++ b/src/Model/TermRelationship.php
@@ -30,7 +30,7 @@
     protected $table = 'term_relationships';
 
     /**
-     * @var array
+     * @var array<int, string>
      */
     protected $primaryKey = ['object_id', 'term_taxonomy_id'];
 
--- a/src/Model/User.php
+++ b/src/Model/User.php
@@ -45,7 +45,7 @@
     protected $primaryKey = 'ID';
 
     /**
-     * @var array
+     * @var array<int, string>
      */
     protected $hidden = ['user_pass'];
 

@ogorzalka

Copy link
Copy Markdown
Member Author

Maintainer decision: held for the next major version. The generics can surface new PHPStan errors in projects that subclass the models (Eloquent's related-model template is invariant), with no runtime change.

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