EventSaucePHP / EventSauce

A pragmatic event sourcing library for PHP with a focus on developer experience.
https://eventsauce.io/
MIT License
817 stars 82 forks source link

Fix incorrect aggregate root ID type on `AggregateRootWithAggregates` #225

Open axlon opened 5 months ago

axlon commented 5 months ago

What does this fix?

The AggregateRootWithAggregates breaks type inference for the aggregate root's ID. When using this trait PHPStan will always infer the type as EventSauce\EventSourcing\AggregateRootId

For example:

final class FooId implements AggregateRootId
{
    public function toString(): string
    {
        return 'foo';
    }

    public static function fromString(string $aggregateRootId): static
    {
        return new self();
    }
}

/**
 * @implements AggregateRoot<FooId>
 */
final class Foo implements AggregateRoot
{
    /**
     * @use AggregateRootWithAggregates<FooId, EventSourcedAggregate>
     */
    use AggregateRootWithAggregates;

    public function weCannotInferKeyType(): void
    {
        dumpType($this->aggregateRootId()); // Dumped type: EventSauce\EventSourcing\AggregateRootId
    }
}

With this PR you'd have to add FooId to the @use statement, after which $this->aggregateRootId() would be typed as FooId.

Something to take note of

While this fixes the mistyping completely, it could be considered a breaking change as adding a new template to a trait will surely cause some PHPStan workflows to fail.