Repository navigation
Conversation
tabennett
force-pushed
the
feature/default-loads-through-relationships
branch
2 times, most recently
from
November 15, 2026 07:50
b1dfb75 to
3a3eec8
Compare
- Add phpstan/phpstan ^2.2 to require-dev and autoload the CodeSleeve\Holloway\PhpStan\Extension namespace - Register dynamic return type extensions so getMapper(), find(), get(), paginate(), and where() resolve to concrete entity and builder types without annotations on consumer mappers - Add level 5 phpstan.neon covering src/ and the extension, with targeted ignores for SoftDeletes, legacy factories, and helpers
- Add @template TEntity and @method forward declarations so fluent query chains preserve the entity type - Annotate entity, builder, and mapper methods for PHPStan level 5 - Type the $onDelete property and the Holloway singleton, and make nullable where()/orWhere() operators explicit - Replace try/catch with array_key_exists in Holloway::getMapper() - Read eager loads from the query tree in Builder::getLoads() - Return void from customMany()/customOne() and drop makeEntity(): mixed
- Resolve getMapper() types from class constants, entity instances, and class-strings, including unions of entities - Type additional forwarded methods: all, makeEntity, makeEntities, instantiateEntity, newCollection, newQueryWithoutScopes, newQueryWithoutScope, and newHollowayBuilder - Return the union of collection and nullable entity from find() when the argument type cannot be narrowed - Align Builder and Mapper @method signatures with the argument types Illuminate accepts (Expression, Closure, iterable, mixed)
- Assert entity, collection, paginator, and builder return types through TypeInferenceTestCase - Cover getMapper() lookups by class constant, entity instance, and class-string, including a union of entity classes - Add a level 8 config over the fixtures so forwarded argument types are validated, not just inferred return types
- Run PHPStan over src/ and the extension on PHP 8.3 - Run the level 8 fixture config to catch argument-type drift in forwarded @method signatures - Install from the lock file for reproducible builds
- Add a static analysis guide covering installation, inferred types, registry lookups, level 6+ generics, and limitations - Link it from the readme - Declare extra.phpstan.includes so phpstan/extension-installer auto-registers the extension
- Accept anything Laravel accepts for where()/orWhere() and the pass-through query methods: untype the Builder::where()/orWhere() operator (it is no longer coerced to a string) and use variadic mixed arguments in the @method tags. - Give Mapper and Builder a default template type so raw Mapper/Builder references (extends Mapper, a Builder parameter in a scope) don't raise missingType.generics. - Return the concrete paginator classes, and drop the class-string annotation on getEntityClassName(), which conflicted with plain string implementations. - Don't replace the return types of methods that a mapper overrides, such as find() or get(). - Add an overriding mapper fixture and type-inference tests for the above.
- Resolve scopeXxx() methods as xxx() on a concrete mapper and anywhere in a query chain from it, with the scope's own parameters (minus $query) checked. Resolve withTrashed(), withoutTrashed() and onlyTrashed() on mappers that use SoftDeletes. - Give Builder a second template type, Builder<TEntity, TMapper>, which the extension sets wherever a builder comes from a concrete mapper. Carry it through the @method tags and builder return types ($this / static). - Share the mapper-to-entity lookup between the extensions in a new EntityTypeResolver. - Fall back to the @method tags for a union of mappers instead of resolving only the first mapper's entity. - Ignore PHPStan's backward compatibility notice for the method reflection class in the project's own analysis. - Add scope, macro and union type-inference tests and update the builder type expectations.
- Add a section on scopes and soft-delete macros, including what is not resolved (mappers from Holloway::getMapper(), bare Builder parameters). - Note that the extension targets PHPStan 2.x.
get() takes no arguments, so get(['id', 'name']) selects every column. Point to select() for limiting columns.
…dReflection PHPStan 2.3 added the abstract method getPureUnlessParameterPassedParameters() to ExtendedMethodReflection. ScopeMethodReflection implements that interface, so with a fresh install the class failed to load with a fatal error as soon as the type inference tests were discovered, and every job that runs the test suite exited with 255. The interface isn't covered by PHPStan's backward compatibility promise, which is why a minor release could add it. Return an empty array, since nothing is known about the purity of a scope or a soft-delete macro, the way PHPStan's own dummy reflection does. The method is simply extra on the 2.2 interface, so older installs are unaffected.
A mapper's $with was only applied to queries run directly on that mapper.
Reached through a relationship it was ignored, because relationships load
raw rows with toBase()->get() and the related Builder's loads were thrown
away along with it.
Tree::buildTree() now adds the default loads of the mapper that a new node
leads to as children of that node. It does this on the same stack it already
builds loads with, so loadData() and mapData() are untouched and each still
walks the finished tree once.
- Loads that were asked for win over defaults, in either order. A default
only fills in what's missing.
- A node that was only passed through on the way to a nested load has null
constraints until a load or a default gives it some, so a default's
constraints still apply to it whatever order the loads are given in.
Loaders already treat null constraints as a no-op.
- Default loads are not added beneath custom relationships, which load their
records with their own query.
- The mappers whose defaults led to a load are tracked along each path. If a
mapper turns up in its own chain its defaults lead back around to
themselves, and a CircularDefaultLoadsException naming the chain is thrown
instead of expanding forever.
Building the tree this way also fixes two bugs in how loads were merged:
- A bare load given after a dotted one, with('pups.collar')->with('pups'),
replaced the node the dotted load had built and dropped its children.
Loads are now merged by node, so the order they're given in no longer
matters (this also keeps a mapper's default 'pups.collar' when a caller
adds a bare 'pups').
- The rest of a dotted path was found with str_replace(), which removes
every occurrence of the prefix and matches inside other names, so
'pups.pack.pups.collar' became 'pack.collar'. It is now split once.
Behavior change: a related mapper with a non-empty $with now loads those
relationships when it's reached through a relationship, which means more
queries (one per relationship). Mappers whose defaults point at each other
now throw instead of silently ignoring the related defaults.
Add tests for merging loads in either order and for default loads through
hasMany and belongsTo, cascading and nested defaults, constraints, custom
relationships, getLoads(), and both cycle cases, with small fixture mappers
that declare a $with.
Describe that a mapper's $with is also loaded when the mapper is reached through a relationship, that loads asked for win over defaults, that custom relationships don't get them, that defaults leading back around to themselves throw a CircularDefaultLoadsException, and that without() can't remove the default loads of a related mapper.
…e::buildTree Rename the variables in buildTree() so they read as what they hold ($mapperChain, $relatedMapper, $remainingPath, $isNewNode, $isDefaultLoad, $defaultName), and describe the method as numbered steps in the body, the way the rest of the class is written. Shorten the docblock to two sentences. No change in behavior.
…e path Adding the default loads of related mappers threw a CircularDefaultLoadsException when a mapper's defaults led back to a mapper that was already being loaded. A pup that defaults to its collar with a collar that defaults to its pup, or a mapper whose default is a relationship to itself, would throw on every query, where it loaded fine before related defaults were added. Keep the mappers on the path from the root to the node being built, starting with the root mapper, and don't add a default load that leads to one of them. Loads that were asked for are never cut off, and the root mapper's own $with still loads one level as it always has. The exception and its helper are removed. Add tests for a pair of mappers whose defaults lead to each other (from either side), a default that leads back to its own mapper, and a path that was asked for coming back around to a mapper, with fixture mappers for the mutual and self-referential cases. Change the belongsTo test to a path that doesn't loop and update the docs.
…r a query Default loads now load whenever a mapper is reached through a relationship, and without() can't remove them because they aren't in the query's own loads. Add withoutDefaultLoads() on the builder, in the same style as withoutGlobalScopes(), to skip every default load for a single query: the $with of the mapper being queried and of the mappers it leads to. Loads that were asked for still load, whichever order they're asked for in. Tree keeps track of which loads came from the root mapper's $with so they can be told apart from loads that were asked for, and Mapper hands its $with to Tree::addDefaultLoads() instead of with(). Add tests and document it.
…onstraints A constraint closure is handed the query that loads a relationship, but only the rows it returns are used: the loads of a query are decided by the tree before any query runs. Calling with(), without() or withoutDefaultLoads() in one silently did nothing. Mark the query that the standard relationships (hasOne, hasMany, belongsTo and belongsToMany) hand to their constraints, and have those three methods throw a BadMethodCallException that points at the outer query instead. Pass the constraints of a custom relationship to its load closure as an optional third argument, so they can be applied to the query the closure builds. Closures that take two arguments are unaffected and ignore them. Add tests for each relationship type and method, for the constraints that are still allowed, and for the custom relationship constraints.
Add a page covering what works, what differs and what throws in a mapper's query API: the three steps a query runs in, constraint closures, select(), default loads and custom relationship constraints. Fix the examples that contradicted it. The nested constraints example called with() inside a constraint closure, which never worked. The limit() examples implied a per-parent limit, and the profile select() example left out the primary key. Describe the arguments of a custom relationship's load and for functions as records, and document the constraints argument.
tabennett
force-pushed
the
feature/default-loads-through-relationships
branch
from
November 15, 2026 21:04
3a3eec8 to
7272eda
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Eager loads now include the default loads (
$with) of related mappers, loads that share a parent merge into one node whatever order they're given in, andwithoutDefaultLoads()skips the defaults for a single query.Closes #15.
What was wrong
$withonly applied when that mapper was queried directly. Reached through a relationship it was ignored, because every relationship loads raw rows withtoBase()->get(), which discards the related builder and its loads.with('pups.collar')->with('pups')droppedcollar, but the reverse order kept it: the bare-name branch ofTree::buildTree()replaced a node a dotted load had already built. A mapper's default'pups.collar'was lost the same way when a caller added a bare'pups'.str_replace("$nodeName.", '', $name), which removes every occurrence and also matches inside other names, sopups.pack.pups.collarbecamepack.collarand threwUknownRelationshipException.with()andwithout()inside a relationship's constraint closure silently did nothing, and constraints given to a custom relationship were silently dropped.What changed
Tree::buildTree()(still iterative, same stack and frame idiom) splits each load once and merges it into the node if it exists. Constraints go on the last segment only, and a node that is just passed through hasnullconstraints.getWith()is added beneath it. Loads that were asked for always win over defaults, in either order. Custom relationships don't get defaults, since they load with their own query.withoutDefaultLoads()on the builder, in the style ofwithoutGlobalScopes(). It skips every default load: the queried mapper's own$withand those of related mappers. Loads you ask for still load, whichever order you call it in.Mapper::newQueryWithoutScopes()now hands$withtoTree::addDefaultLoads()so defaults can be told apart from loads that were asked for.getLoads()still lists the mapper's own defaults until you callwithoutDefaultLoads().with(),without()andwithoutDefaultLoads()throw aBadMethodCallExceptionthere, pointing at the outer query.loadData()andmapData()are unchanged: still one walk of the finished tree each, no extra pass and no new recursion. Entities are hydrated exactly as before.Behavior changes (read before releasing)
$withnow loads those relations when it's reached through a relationship: more queries, one per relationship, and larger entities.collar, Collar defaults topup) load the way they did before: the queried mapper's own$withone level deep, with the default that leads back skipped.without('pups.collar')removes an explicit dotted load.with(),without()andwithoutDefaultLoads()inside a constraint closure now throw, where they used to do nothing.without(), because they aren't in the query's own list of loads. UsewithoutDefaultLoads()for the query.Buildergains a publicforRelationLoad(), the marker the loaders use.newQueryWithoutScopes()no longer callswith()for the defaults, so aBuildersubclass that overrideswith()won't see them pass through it.Worth searching your apps for before upgrading: related mappers with a
$with,with()orwithout()inside constraint closures, and constraints on custom relationships (which now reach the third argument of the load closure).Docs
docs/references/query-builder-api.md: how a query runs, what works and what throws in a constraint closure, theselect()contract, default loads and custom relationship constraints.with()inside a constraint closure, twolimit()examples implied a per-parent limit, and the profileselect()example left out the primary key.custom.mdalso called raw records "entities".Tests
EagerLoadMergeTest,DefaultLoadsTestandRelationConstraintsTest, with small fixture mappers for the mutual, self-referential and constrained cases.