0

In my code I created an EventFactory like this:

private array $events = [
    'post_created' => PostCreatedEvent::class,
    'exercise_executed' => ExerciseExecutedEvent::class,
];

public function fromTopicAndData(string $topic, array $data) : Event
{
    if (! array_key_exists($topic, $this->events)) {
        throw new Exception('Invalid Topic');
    }

    $event = ($this->events)[$topic];
    return $event::createFromData($data);
}

Both PostCreatedEvent and ExerciseExecutedEvent extends an abstract class Event.

Can you tell me if there is a way to annotate the array in such a way as not to receive error from Psalm?

1 Answers1

2

Assuming Event class declares createFromData() method the following docblock should do the trick:

/** @var array<string, class-string<Event>> */
private array $events = [
    'post_created' => PostCreatedEvent::class,
    'exercise_executed' => ExerciseExecutedEvent::class,
];

Live demo: https://psalm.dev/r/da11fc8d8c

weirdan
  • 2,499
  • 23
  • 27