public function provideListeners(ListenerAcceptorInterface $acceptor)
 {
     $acceptor->addListener('ip', function ($event, $ip) {
         $this->client->get('https://freegeoip.net/json/' . $ip, ['future' => true])->then(function (Response $response) {
             $this->emitter->emit('sse', ['type' => 'geo', 'payload' => $response->json()['region_name']]);
         });
     });
 }
 public function provideListeners(ListenerAcceptorInterface $acceptor)
 {
     $acceptor->addListener('lookup', function ($event, $hostname) {
         $this->resolver->resolve($hostname)->then(function ($ip) {
             $this->emitter->emit('ip', $ip);
             $this->emitter->emit('sse', ['type' => 'dns', 'payload' => $ip]);
         });
     });
 }
Exemplo n.º 3
0
 /**
  * @param EventInterface|string $event
  * @throws \InvalidArgumentException
  * @return bool true if emitted, false otherwise
  */
 private function emitEvent($event)
 {
     if (is_null($this->eventEmitter)) {
         return false;
     }
     if (!is_string($event) && !$event instanceof EventInterface) {
         throw new \InvalidArgumentException('Event must be either be of type "string" or instance of League\\Event\\EventInterface');
     }
     $this->eventEmitter->emit($event);
     return true;
 }
 public function provideListeners(ListenerAcceptorInterface $acceptor)
 {
     $acceptor->addListener('lookup', function ($event, $hostname) {
         $this->client->get('http://' . $hostname . '/', ['future' => true])->then(function (Response $response) {
             if (preg_match('/<title>(.+)<\\/title>/', $response->getBody()->getContents(), $matches) && isset($matches[1])) {
                 $title = $matches[1];
                 $this->emitter->emit('sse', ['type' => 'title', 'payload' => $title]);
             }
         });
     });
 }
Exemplo n.º 5
0
 /**
  * Emits the events corresponding to applying the provided input on the provided object.
  *
  * @param Input $input
  * @param Stateful $object
  * @param Context $context
  * @param State $nextState
  *
  * @return void
  *
  * @throws StateTransitionFailed
  */
 private function emitEvents(Input $input, Stateful $object, Context $context, State $nextState)
 {
     /** @var Event $event */
     foreach ($this->eventProvider($input, $object->getCurrentState()) as $event) {
         if (!$this->emitter->hasListeners($event->getName())) {
             continue;
         }
         if ($this->emitter->emit($event, $object, $context, $input, $nextState)->isPropagationStopped()) {
             $this->emitter->emit(Event::named('failed'), $object, $context, $input, $nextState);
             throw new StateTransitionFailed($input, $object, $context, $nextState);
         }
     }
 }
Exemplo n.º 6
0
 /**
  * @param BoardFactory $boardFactory
  *
  * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
  * @throws \React\Socket\ConnectionException
  */
 public function run(BoardFactory $boardFactory)
 {
     $emitter = new Emitter();
     $wamp = new WampConnector($emitter);
     $webSocket = new \React\Socket\Server($this->eventLoop);
     $webSocket->listen(self::SOCKET_LISTEN_PORT, '0.0.0.0');
     $board = $boardFactory->initialize();
     new IoServer(new HttpServer(new WsServer(new WampServer($wamp))), $webSocket);
     $emitter->addListener(QuestionSubscriptionEvent::class, function (QuestionSubscriptionEvent $event) use($wamp, $board) {
         $wamp->onQuestionSubscribe($board->getCategories(), $event->getSessionId());
     });
     $emitter->addListener(ContestantScoreSubscriptionEvent::class, function (ContestantScoreSubscriptionEvent $event) use($wamp, $board) {
         $wamp->onContestantScoreSubscription($board->getContestants(), $event->getSessionId());
     });
     $emitter->addListener(BuzzerStatusSubscriptionEvent::class, function (BuzzerStatusSubscriptionEvent $event) use($wamp, $board) {
         $wamp->onBuzzerStatusChange($board->getBuzzerStatus(), [], [$event->getSessionId()]);
     });
     $emitter->addListener(BuzzerResolutionEvent::class, function (BuzzerResolutionEvent $event) use($wamp) {
         //TODO Store this event
         echo 'Buzzer Resolution: ' . $event->getResolution()->getContestant()->getName() . " buzzed in ({$event->getResolution()->getTime()}ms)\n";
         $wamp->onBuzzerResolution($event->getResolution());
     });
     $emitter->addListener(QuestionAnswerEvent::class, function (QuestionAnswerEvent $event) use($wamp, $board, $emitter) {
         try {
             $questionAnswer = $event->getQuestionAnswer();
             $board->addScore($questionAnswer->getContestant(), $questionAnswer->getRealValue());
             $wamp->onQuestionAnswer($questionAnswer);
         } catch (ContestantNotFoundException $exception) {
             echo $exception->getMessage();
             // TODO handle exception
         }
         if ($questionAnswer->isCorrect()) {
             $emitter->emit(new QuestionDismissalEvent(new QuestionDismissal($questionAnswer->getCategory(), $questionAnswer->getValue())));
             return;
         }
         $emitter->emit(new BuzzerStatusChangeEvent(new BuzzerStatus(true)));
     });
     $emitter->addListener(QuestionDisplayRequestEvent::class, function (QuestionDisplayRequestEvent $event) use($wamp, $board) {
         try {
             $question = $board->getQuestionByCategoryAndValue($event->getCategoryName(), $event->getValue());
             $question->setUsed();
             $wamp->onQuestionDisplay($question, $event->getCategoryName());
         } catch (QuestionNotFoundException $exception) {
             //TODO log this somewhere.
             echo "Error occured, could not find question in category: {$event->getCategoryName()} valued at: {$event->getValue()}";
         }
     });
     $emitter->addListener(DailyDoubleBetEvent::class, function (DailyDoubleBetEvent $event) use($wamp, $board) {
         try {
             $question = $board->getQuestionByCategoryAndValue($event->getCategory(), $event->getValue());
         } catch (QuestionNotFoundException $e) {
             // TODO
         }
         $wamp->onDailyDoubleBetRecieved($question, $event->getCategory(), $event->getBet());
     });
     $emitter->addListener(QuestionDismissalEvent::class, function (QuestionDismissalEvent $event) use($wamp, $board) {
         $dismissal = $event->getDismissal();
         $wamp->onQuestionDismiss($dismissal);
     });
     $emitter->addListener(BuzzReceivedEvent::class, function (BuzzReceivedEvent $event) use($board, $emitter) {
         if (!$board->getBuzzerStatus()->isActive()) {
             // The buzzer isn't active, so there's nothing to do.
             return;
         }
         if ($board->getResolver()->isEmpty()) {
             // If this is the first buzz, then we want to resolve it after the timeout.
             $this->eventLoop->addTimer($this->buzzer_resolve_timeout, function () use($board, $emitter) {
                 $resolution = $board->resolveBuzzes();
                 $emitter->emit(new BuzzerResolutionEvent($resolution));
             });
         }
         // TODO store this event
         echo 'Buzz in (' . $event->getContestant()->getName() . '): ' . $event->getDifference() . "ms \n";
         $board->getResolver()->addBuzz($event);
     });
     $emitter->addListener(BuzzerStatusChangeEvent::class, function (BuzzerStatusChangeEvent $event) use($wamp, $board) {
         $board->setBuzzerStatus($event->getBuzzerStatus());
         $wamp->onBuzzerStatusChange($event->getBuzzerStatus());
     });
     $emitter->addListener(FinalJeopardyCategoryRequest::class, function (FinalJeopardyCategoryRequest $event) use($wamp, $board) {
         $wamp->onFinalJeopardyRequest('category', $board->getFinalJeopardyClue());
     });
     $emitter->addListener(FinalJeopardyClueRequest::class, function (FinalJeopardyClueRequest $event) use($wamp, $board) {
         $wamp->onFinalJeopardyBetCollectionRequest();
         // We're going to wait for a set time
         //TODO this doesn't work for some reason in every case, so we simply don't close the acceptance of responses.
         $this->eventLoop->addTimer($this->final_jeopardy_collection_timeout, function () use($wamp, $board) {
             if (!$board->getFinalJeopardy()->hasAllBets()) {
                 //TODO logging
                 echo "Did not recieve all bets.\n";
                 $missingbets = $board->getFinalJeopardy()->getMissingBets();
                 $missingbets = implode(', ', $missingbets);
                 echo "Require bets from: {$missingbets}\n";
             }
             $wamp->onFinalJeopardyRequest('clue', $board->getFinalJeopardyClue());
         });
     });
     $emitter->addListener(ContestantScoreChangeEvent::class, function (ContestantScoreChangeEvent $event) use($wamp, $board) {
         try {
             $board->addScore(new Contestant($event->getContestant()), $event->getScoreChange());
         } catch (ContestantNotFoundException $e) {
             //TODO
         }
         $contestant = $board->getContestants()->first(function ($key, Contestant $contestant) use($event) {
             return $contestant->getName() === $event->getContestant();
         });
         $wamp->onContestantScoreUpdate($contestant);
     });
     $emitter->addListener(FinalJeopardyBetEvent::class, function (FinalJeopardyBetEvent $event) use($wamp, $board) {
         $finalJeopardy = $board->getFinalJeopardy();
         $finalJeopardy->setBet($event->getContestant(), $event->getBet());
     });
     $emitter->addListener(FinalJeopardyAnswerRequest::class, function (FinalJeopardyAnswerRequest $event) use($wamp, $board) {
         $wamp->onFinalJeopardyAnswerCollectionRequest();
         $this->eventLoop->addTimer($this->final_jeopardy_collection_timeout, function () use($wamp, $board) {
             if (!$board->getFinalJeopardy()->hasAllAnswers()) {
                 //TODO logging
                 echo "Did not receive all final jeopardy answers!\n";
                 $missingAnswers = $board->getFinalJeopardy()->getMissingAnswers();
                 $missingAnswers = implode(', ', $missingAnswers);
                 echo "Require answers from: {$missingAnswers}\n";
             }
             $wamp->onFinalJeopardyRequest('answer', $board->getFinalJeopardyClue());
         });
     });
     $emitter->addListener(FinalJeopardyAnswerEvent::class, function (FinalJeopardyAnswerEvent $event) use($wamp, $board) {
         $finalJeopardy = $board->getFinalJeopardy();
         if ($finalJeopardy->hasAnswer($event->getContestant())) {
             //TODO logging
             echo "{$event->getContestant()} has already submitted a final answer";
             return;
         }
         $finalJeopardy->setAnswer($event->getContestant(), $event->getAnswer());
     });
     $emitter->addListener(FinalJeopardyResponseRequest::class, function (FinalJeopardyResponseRequest $event) use($wamp, $board) {
         $finalJeopardy = $board->getFinalJeopardy();
         if (!$finalJeopardy->hasAnswer($event->getContestant())) {
             //TODO logging
             $response = new FinalJeopardyQuestionResponse($event->getContestant(), 0, 'No answer, Troy');
             $wamp->onFinalJeopardyResponse($response);
             return;
         }
         $wamp->onFinalJeopardyResponse($finalJeopardy->getResponse($event->getContestant()));
     });
     $this->eventLoop->run();
 }
 /**
  * @param EventInterface $event
  */
 public function emit(EventInterface $event)
 {
     $this->emitter->emit($event);
 }
Exemplo n.º 8
0
 /**
  * A client is attempting to publish content to a subscribed connections on a URI
  *
  * @param \Ratchet\ConnectionInterface $conn
  * @param string|Topic $topic The topic the user has attempted to publish to
  * @param string $event Payload of the publish
  * @param array $exclude A list of session IDs the message should be excluded from (blacklist)
  * @param array $eligible A list of session Ids the message should be send to (whitelist)
  */
 function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible)
 {
     switch ((string) $topic) {
         case self::BUZZER_TOPIC:
             $contestant = new Contestant($event['name']);
             $this->emitter->emit(new BuzzReceivedEvent($contestant, $event['difference']));
             break;
         case self::BUZZER_STATUS_TOPIC:
             $this->emitter->emit(new BuzzerStatusChangeEvent(new BuzzerStatus($event['active'])));
             break;
         case self::CONTESTANT_SCORE:
             if (!isset($event['diff']) || !isset($event['contestant'])) {
                 // TODO logging
                 echo "Invalid parameters sent to update contestant score\n";
                 print_r($event);
                 break;
             }
             $this->emitter->emit(new ContestantScoreChangeEvent($event['contestant'], $event['diff']));
             break;
         case self::QUESTION_DISPLAY_TOPIC:
             if (!isset($event['category']) || !isset($event['value'])) {
                 //TODO log this
                 echo "Did not receive proper question request, did not have a category or value\n";
                 break;
             }
             $this->emitter->emit(new QuestionDisplayRequestEvent($event['category'], $event['value']));
             break;
         case self::QUESTION_ANSWER_QUESTION:
             if (!isset($event['category']) || !isset($event['value']) || !isset($event['contestant'])) {
                 //TODO log this
                 echo "Did not receive proper question answer request, did not have a category or value or playerName\n";
                 break;
             }
             $questionAnswerEvent = new Question\QuestionAnswerEvent(new Question\QuestionAnswer($event['category'], $event['value'], new Contestant($event['contestant']), isset($event['correct']) ? $event['correct'] : false));
             if (isset($event['bet'])) {
                 $questionAnswerEvent->getQuestionAnswer()->setBet($event['bet']);
             }
             $this->emitter->emit($questionAnswerEvent);
             break;
         case self::QUESTION_DISMISS_TOPIC:
             if (!isset($event['category']) || !isset($event['value'])) {
                 //TODO log this
                 echo "Did not receive proper dismiss request, did not have a category or value\n";
                 break;
             }
             $dismissal = new Question\QuestionDismissalEvent(new Question\QuestionDismissal($event['category'], $event['value']));
             $this->emitter->emit($dismissal);
             break;
         case self::DAILY_DOUBLE_BET_TOPIC:
             if (!isset($event['category']) || !isset($event['value']) || !isset($event['bet'])) {
                 //TODO logging
                 echo "Recieved invalid daily double bet\n";
                 break;
             }
             $this->emitter->emit(new Question\DailyDouble\DailyDoubleBetEvent($event['value'], $event['category'], $event['bet']));
             break;
         case self::FINAL_JEOPARDY_TOPIC:
             if (!isset($event['content'])) {
                 //TODO logging
                 echo "Recieved invalid final jeopardy topic request - no content selection";
                 break;
             }
             if ($event['content'] == "category") {
                 $this->emitter->emit(new Question\FinalJeopardy\FinalJeopardyCategoryRequest());
                 break;
             }
             if ($event['content'] == "clue") {
                 echo "Recieved clue request";
                 $this->emitter->emit(new Question\FinalJeopardy\FinalJeopardyClueRequest());
                 break;
             }
             if ($event['content'] == "answer") {
                 $this->emitter->emit(new Question\FinalJeopardy\FinalJeopardyAnswerRequest());
                 break;
             }
             break;
         case self::FINAL_JEOPARDY_RESPONSES_TOPIC:
             if (!isset($event['contestant']) || !isset($event['type'])) {
                 //TODO logging
                 echo "Invalid jeopardy response, did not specify type or did not include contestant\n";
                 print_r($event);
                 break;
             }
             if ($event['type'] == "bet") {
                 if (!isset($event['bet'])) {
                     //TODO logging
                     echo "Invalid final jeopardy bet, did not include a bet value\n";
                     print_r($event);
                     break;
                 }
                 $this->emitter->emit(new Question\FinalJeopardy\FinalJeopardyBetEvent($event['contestant'], $event['bet']));
                 break;
             }
             if ($event['type'] == "answer") {
                 if (!isset($event['answer'])) {
                     //TODO Logging
                     echo "Invalid final jeopardy answer, did not include an answer response\n";
                     print_r($event);
                     break;
                 }
                 $this->emitter->emit(new Question\FinalJeopardy\FinalJeopardyAnswerEvent($event['contestant'], $event['answer']));
                 break;
             }
             break;
         case self::FINAL_JEOPARDY_ANSWER_TOPIC:
             //TODO error checking
             $this->emitter->emit(new Question\FinalJeopardy\FinalJeopardyResponseRequest($event['contestant']));
             break;
         default:
             break;
     }
 }
Exemplo n.º 9
0
 /**
  * Emit an event
  *
  * @param string event name
  * @param array additional data
  * @return League\Event\Event
  */
 public function emit($name, $data = [])
 {
     self::$emitter->emit($name, $data);
 }
 /**
  * @inheritDoc
  */
 public function handle(DomainMessage $domainMessage)
 {
     $this->emitter->emit($domainMessage->getPayload());
 }
 protected function handleLookup(Response $response, $hostName)
 {
     $this->emitter->emit('lookup', $hostName);
     $response->writeHead(200);
     $response->end('{}');
 }