-
Notifications
You must be signed in to change notification settings - Fork 7
Narrow Cake\ORM\Association::find() return to SelectQuery<TargetEntity> #68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
rochamarcelo
merged 2 commits into
CakeDC:4.next-cake5
from
dereuromark:feature/association-find-narrowing
May 21, 2026
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * | ||
| * Licensed under The MIT License | ||
| * Redistributions of files must retain the above copyright notice. | ||
| * | ||
| * @copyright Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * @license MIT License (http://www.opensource.org/licenses/mit-license.php) | ||
| */ | ||
|
|
||
| namespace CakeDC\PHPStan\Traits; | ||
|
|
||
| use Cake\Utility\Inflector; | ||
|
|
||
| /** | ||
| * Resolves the entity class FQCN that belongs to a given table class FQCN, | ||
| * using the standard CakePHP convention (`Foo\Model\Table\BarsTable` → | ||
| * `Foo\Model\Entity\Bar`). | ||
| */ | ||
| trait EntityClassFromTableClassTrait | ||
| { | ||
| /** | ||
| * @param string $className Fully-qualified table class name. | ||
| * @return string|null Fully-qualified entity class name, or null if the | ||
| * input does not match the `*\Model\Table\*Table` convention. | ||
| */ | ||
| protected function getEntityClassByTableClass(string $className): ?string | ||
| { | ||
| $parts = explode('\\', $className); | ||
| $count = count($parts); | ||
| $nameIndex = $count - 1; | ||
| $folderIndex = $count - 2; | ||
| if ($count < 3 || $parts[$folderIndex] !== 'Table') { | ||
| return null; | ||
| } | ||
| $name = str_replace('Table', '', $parts[$nameIndex]); | ||
| $name = Inflector::singularize($name); | ||
| $parts[$folderIndex] = 'Entity'; | ||
| $parts[$nameIndex] = $name; | ||
|
|
||
| return implode('\\', $parts); | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * | ||
| * Licensed under The MIT License | ||
| * Redistributions of files must retain the above copyright notice. | ||
| * | ||
| * @copyright Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * @license MIT License (http://www.opensource.org/licenses/mit-license.php) | ||
| */ | ||
|
|
||
| namespace CakeDC\PHPStan\Type; | ||
|
|
||
| use Cake\ORM\Association; | ||
| use Cake\ORM\Query\SelectQuery; | ||
| use CakeDC\PHPStan\Traits\EntityClassFromTableClassTrait; | ||
| use PhpParser\Node\Expr\MethodCall; | ||
| use PHPStan\Analyser\Scope; | ||
| use PHPStan\Reflection\MethodReflection; | ||
| use PHPStan\Type\DynamicMethodReturnTypeExtension; | ||
| use PHPStan\Type\Generic\GenericObjectType; | ||
| use PHPStan\Type\ObjectType; | ||
| use PHPStan\Type\Type; | ||
|
|
||
| /** | ||
| * Narrows the return type of {@see Association::find()} to | ||
| * `SelectQuery<TargetEntity>`. | ||
| * | ||
| * Cake core declares `Association::find()` as | ||
| * `\Cake\ORM\Query\SelectQuery<EntityInterface|array>` — it does not propagate | ||
| * the target table's `TEntity` template parameter. As a result, chains such as | ||
| * `$this->Articles->Users->find()->first()` resolve to `EntityInterface|null` | ||
| * instead of `User|null`, forcing every call-site to add inline `@var` | ||
| * annotations. | ||
| * | ||
| * This extension reads the association's target table type — once | ||
| * {@see \CakeDC\PHPStan\PhpDoc\TableAssociationTypeNodeResolverExtension} has | ||
| * converted the intersection `BelongsTo&UsersTable` into the generic | ||
| * `BelongsTo<UsersTable>` — derives the entity class via the standard CakePHP | ||
| * naming convention, and replaces the return type with | ||
| * `SelectQuery<UserEntity>`. | ||
| * | ||
| * Hydration-disabled queries are not detected here; PHPStan cannot follow | ||
| * `$query->disableHydration()` calls regardless of which extension produces | ||
| * the type, so narrowing to the entity is at least as accurate as the current | ||
| * `EntityInterface|array` union and strictly better for the common hydrated | ||
| * case. | ||
| */ | ||
| class AssociationFindDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension | ||
| { | ||
| use EntityClassFromTableClassTrait; | ||
|
|
||
| /** | ||
| * @inheritDoc | ||
| */ | ||
| public function getClass(): string | ||
| { | ||
| return Association::class; | ||
| } | ||
|
|
||
| /** | ||
| * @inheritDoc | ||
| */ | ||
| public function isMethodSupported(MethodReflection $methodReflection): bool | ||
| { | ||
| return $methodReflection->getName() === 'find'; | ||
| } | ||
|
|
||
| /** | ||
| * @param \PHPStan\Reflection\MethodReflection $methodReflection | ||
| * @param \PhpParser\Node\Expr\MethodCall $methodCall | ||
| * @param \PHPStan\Analyser\Scope $scope | ||
| * @return \PHPStan\Type\Type|null | ||
| */ | ||
| public function getTypeFromMethodCall( | ||
| MethodReflection $methodReflection, | ||
| MethodCall $methodCall, | ||
| Scope $scope, | ||
| ): ?Type { | ||
| $tableClass = $this->extractTargetTableClass($scope, $methodCall); | ||
| if ($tableClass === null) { | ||
| return null; | ||
| } | ||
|
|
||
| $entityClass = $this->getEntityClassByTableClass($tableClass); | ||
| if ($entityClass === null || !class_exists($entityClass)) { | ||
| return null; | ||
| } | ||
|
|
||
| return new GenericObjectType(SelectQuery::class, [new ObjectType($entityClass)]); | ||
| } | ||
|
|
||
| /** | ||
| * Returns the target table FQCN from an `Association<TargetTable>` generic | ||
| * type, or null if the association is not generic-typed. | ||
| * | ||
| * @param \PHPStan\Analyser\Scope $scope | ||
| * @param \PhpParser\Node\Expr\MethodCall $methodCall | ||
| * @return string|null | ||
| */ | ||
| protected function extractTargetTableClass(Scope $scope, MethodCall $methodCall): ?string | ||
| { | ||
| $calledOnType = $scope->getType($methodCall->var); | ||
| // GenericObjectType is the only way to read template parameter types | ||
| // from a typed Association — there is no non-deprecated equivalent in | ||
| // PHPStan 2.x yet. | ||
| // @phpstan-ignore-next-line phpstanApi.instanceofType | ||
| if (!$calledOnType instanceof GenericObjectType) { | ||
| return null; | ||
| } | ||
|
|
||
| $typeArgs = $calledOnType->getTypes(); | ||
| if (count($typeArgs) === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| $tableClassNames = $typeArgs[0]->getObjectClassNames(); | ||
| if (count($tableClassNames) === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| return $tableClassNames[0]; | ||
| } | ||
| } | ||
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
52 changes: 52 additions & 0 deletions
52
tests/TestCase/Type/AssociationFindDynamicReturnTypeExtensionTest.php
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * | ||
| * Licensed under The MIT License | ||
| * Redistributions of files must retain the above copyright notice. | ||
| * | ||
| * @copyright Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * @license MIT License (http://www.opensource.org/licenses/mit-license.php) | ||
| */ | ||
|
|
||
| namespace CakeDC\PHPStan\Test\TestCase\Type; | ||
|
|
||
| use PHPUnit\Framework\TestCase; | ||
|
|
||
| class AssociationFindDynamicReturnTypeExtensionTest extends TestCase | ||
| { | ||
| /** | ||
| * Association::find()->first()/firstOrFail() must narrow to the target | ||
| * table's entity type. | ||
| * | ||
| * @return void | ||
| */ | ||
| public function testAssociationFindNarrowsToTargetEntity(): void | ||
| { | ||
| $output = $this->runPhpStan(__DIR__ . '/Fake/AssociationFindCorrectUsage.php'); | ||
| static::assertStringContainsString('[OK] No errors', $output); | ||
| } | ||
|
|
||
| /** | ||
| * Run PHPStan on a file and return the output. | ||
| * | ||
| * @param string $file File to analyze. | ||
| * @return string | ||
| */ | ||
| private function runPhpStan(string $file): string | ||
| { | ||
| $configFile = dirname(__DIR__, 3) . '/extension.neon'; | ||
| $command = sprintf( | ||
| 'cd %s && vendor/bin/phpstan analyze %s --level=max --configuration=%s --no-progress 2>&1', | ||
| escapeshellarg(dirname(__DIR__, 3)), | ||
| escapeshellarg($file), | ||
| escapeshellarg($configFile), | ||
| ); | ||
|
|
||
| exec($command, $output, $exitCode); | ||
|
|
||
| return implode("\n", $output); | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * | ||
| * Licensed under The MIT License | ||
| * Redistributions of files must retain the above copyright notice. | ||
| * | ||
| * @copyright Copyright 2025, Cake Development Corporation (https://www.cakedc.com) | ||
| * @license MIT License (http://www.opensource.org/licenses/mit-license.php) | ||
| */ | ||
|
|
||
| namespace CakeDC\PHPStan\Test\TestCase\Type\Fake; | ||
|
|
||
| use App\Model\Table\NotesTable; | ||
| use function PHPStan\Testing\assertType; | ||
|
|
||
| /** | ||
| * Exercises {@see \CakeDC\PHPStan\Type\AssociationFindDynamicReturnTypeExtension}. | ||
| * | ||
| * `Cake\ORM\Association::find()` is declared in Cake core as | ||
| * `SelectQuery<EntityInterface|array>` — the target entity type is lost. | ||
| * The extension restores it by reading the association's target table type | ||
| * (provided by {@see \CakeDC\PHPStan\PhpDoc\TableAssociationTypeNodeResolverExtension}) | ||
| * and returning `SelectQuery<TargetEntity>`. | ||
| * | ||
| * Note that this fixture only asserts the SelectQuery template parameter, | ||
| * not the downstream `->first()` / `->firstOrFail()` return type. Those depend | ||
| * on Cake core's per-method `@return TSubject|null` / `@return TSubject` | ||
| * annotations (cakephp/cakephp#19439, merged for 5.3.6). On older Cake | ||
| * versions `first()` still returns `mixed`; the entity narrowing kicks in | ||
| * automatically once consumers upgrade. | ||
| */ | ||
| class AssociationFindCorrectUsage | ||
| { | ||
| public function narrowsSelectQueryGeneric(NotesTable $notes): void | ||
| { | ||
| // Sanity check: the existing TableAssociationTypeNodeResolverExtension | ||
| // turns `BelongsTo&UsersTable` into the generic association type. | ||
| assertType('Cake\ORM\Association\BelongsTo<App\Model\Table\UsersTable>', $notes->MyUsers); | ||
|
|
||
| // This is what the new extension contributes: the SelectQuery is | ||
| // templated with the target table's entity type instead of the | ||
| // default `EntityInterface|array`. | ||
| assertType( | ||
| 'Cake\ORM\Query\SelectQuery<App\Model\Entity\User>', | ||
| $notes->MyUsers->find(), | ||
| ); | ||
| } | ||
| } |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.