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 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.