/** * Determines a winner from the list of buzzes accumulated. * * Note: This method is destructive, and will clear the list of buzzes on completion. * @return BuzzerResolution */ public function resolve() { if ($this->isEmpty()) { return BuzzerResolution::createFailure(); } /** @var BuzzReceivedEvent $winner */ $winner = $this->buzzes->reduce(function (BuzzReceivedEvent $carry, BuzzReceivedEvent $event) { if ($event->getDifference() < $carry->getDifference()) { return $event; } return $carry; }, $this->buzzes->first()); $resolution = BuzzerResolution::createSuccess($winner->getContestant(), $winner->getDifference()); $this->buzzes = new Collection(); return $resolution; }
/** * We have resolved who buzzed in first, notify the relevant entities. * * @param BuzzerResolution $resolution */ public function onBuzzerResolution(BuzzerResolution $resolution) { // Is anyone subscribed to buzzer events right now? if (!array_key_exists(self::BUZZER_TOPIC, $this->subscribedTopics)) { return; } $this->subscribedTopics[self::BUZZER_TOPIC]->broadcast($resolution->toJson()); }