|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Bug11857; |
| 4 | + |
| 5 | +use function PHPStan\Testing\assertType; |
| 6 | + |
| 7 | +abstract class Model |
| 8 | +{ |
| 9 | + /** @return BelongsTo<*, *> */ |
| 10 | + public function belongsTo(string $related): BelongsTo |
| 11 | + { |
| 12 | + return new BelongsTo(); |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * @template TRelatedModel of Model |
| 18 | + * @template TDeclaringModel of Model |
| 19 | + */ |
| 20 | +class BelongsTo {} |
| 21 | + |
| 22 | +class User extends Model {} |
| 23 | + |
| 24 | +class Post extends Model |
| 25 | +{ |
| 26 | + /** @return BelongsTo<User, $this> */ |
| 27 | + public function user(): BelongsTo |
| 28 | + { |
| 29 | + return $this->belongsTo(User::class); |
| 30 | + } |
| 31 | + |
| 32 | + /** @return BelongsTo<User, self> */ |
| 33 | + public function userSelf(): BelongsTo |
| 34 | + { |
| 35 | + /** @phpstan-ignore return.type */ |
| 36 | + return $this->belongsTo(User::class); |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +class ChildPost extends Post {} |
| 41 | + |
| 42 | +final class Comment extends Model |
| 43 | +{ |
| 44 | + // This model is final, so either of these |
| 45 | + // two methods would work. It seems that |
| 46 | + // PHPStan is automatically converting the |
| 47 | + // `$this` to a `self` type in the user docblock, |
| 48 | + // but it is not doing so likewise for the `$this` |
| 49 | + // that is returned by the dynamic return extension. |
| 50 | + |
| 51 | + /** @return BelongsTo<User, $this> */ |
| 52 | + public function user(): BelongsTo |
| 53 | + { |
| 54 | + return $this->belongsTo(User::class); |
| 55 | + } |
| 56 | + |
| 57 | + /** @return BelongsTo<User, self> */ |
| 58 | + public function user2(): BelongsTo |
| 59 | + { |
| 60 | + /** @phpstan-ignore return.type */ |
| 61 | + return $this->belongsTo(User::class); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +function test(ChildPost $child): void |
| 66 | +{ |
| 67 | + assertType('Bug11857\BelongsTo<Bug11857\User, Bug11857\ChildPost>', $child->user()); |
| 68 | + // This demonstrates why `$this` is needed in non-final models |
| 69 | + assertType('Bug11857\BelongsTo<Bug11857\User, Bug11857\Post>', $child->userSelf()); // should be: Bug11857\BelongsTo<Bug11857\User, Bug11857\ChildPost> |
| 70 | +} |
0 commit comments