/**
  * @param SecureRandomInterface $random From security.secure_random
  * @param $phase
  * @param EGGame $game
  * @param User $player
  * @return EGPlaySession
  */
 public static function make(SecureRandomInterface $random, $phase, EGGame $game, User $player = null)
 {
     $session = new EGPlaySession();
     $session->setGame($game);
     $session->setPlayer($player);
     $session->setPhase($phase);
     $session->setStartDate(new \DateTime('now'));
     $session->setIsCompleted(false);
     $session->setScore(0);
     $session->id = bin2hex($random->nextBytes(20));
     return $session;
 }
 /**
  * @param $id
  * @param string $slug
  * @return array
  *
  * @Route("/evolution-games/play/{id}/{slug}", name="eg_play")
  * @Template
  */
 public function playAction($id, $slug = '')
 {
     $user = $this->getUser();
     $game = $this->repo('EGGame')->find($id);
     $playSessionRepo = $this->repo('EGPlaySession');
     if (!$game) {
         $this->flash('error', "Uhh ...");
         return $this->redirectRoute('eg_qualifier');
     }
     /** @var SecureRandomInterface $random */
     $random = $this->get('security.secure_random');
     $phase = $game->getPlaySessionPhase();
     /**
      * Logic specifically for contest plays goes here.
      *
      * 1. Is this the first time they've ever played this game? Free play.
      * 2. Do they have 0 tokens? Free play.
      * 3. Is it not a free play and they have tokens? Subtract a token.
      */
     $freePlay = false;
     $noTokens = false;
     if ($user and ($phase == EGPlaySession::PHASE_CONTEST or $phase == EGPlaySession::PHASE_CHAMPIONSHIP)) {
         if (!$playSessionRepo->findOneBy(['player' => $user->getId(), 'game' => $game->getId(), 'isCompleted' => true])) {
             $freePlay = true;
             $phase = EGPlaySession::PHASE_FREEPLAY;
         }
         if (!$freePlay and $user->getTokens() == 0) {
             $noTokens = true;
             $phase = EGPlaySession::PHASE_FREEPLAY;
         }
         if (!$freePlay and !$noTokens) {
             $user->setTokens($user->getTokens() - 1);
         }
     }
     $session = null;
     // Don't create play sessions if not logged in.
     if ($user) {
         // Reuse an old play session if one's available?
         $session = $playSessionRepo->findOneBy(['player' => $user->getId(), 'game' => $game->getId(), 'phase' => $phase, 'isCompleted' => false]);
         if ($session) {
             $session->setStartDate(new \DateTime('now'));
         } else {
             $session = EGPlaySession::make($random, $phase, $game, $user);
             $this->em()->persist($session);
         }
         $this->em()->flush();
     }
     $gameParameters = ['session_id' => $session ? $session->getId() : null, 'completion_url' => $this->generateUrl('eg_game', ['id' => $id, 'slug' => $slug, 'session' => $session ? $session->getId() : null], UrlGeneratorInterface::ABSOLUTE_URL), 'api_endpoint' => (strpos($this->getRequest()->getHttpHost(), 'gotchosen.dev') === false ? 'https://' : 'http://') . $this->getRequest()->getHttpHost() . '/evolution-games/api/v1'];
     $flashVars = http_build_query(['session_id' => $gameParameters['session_id'], 'completion_url' => $gameParameters['completion_url'], 'api_endpoint' => $gameParameters['api_endpoint']]);
     return ['flashVars' => $flashVars, 'gameParameters' => $gameParameters, 'game' => $game, 'gameId' => $id, 'freePlay' => $freePlay, 'noTokens' => $noTokens];
 }
 /**
  * @param Request $request
  * @throws AccessDeniedException
  * @return array
  *
  * @Route("/evolution-games/manage", name="eg_manage")
  * @Template
  */
 public function manageAction(Request $request)
 {
     return $this->redirectRoute('eg_scholarship');
     /** @var User $user */
     $user = $this->getUser();
     if ($user === null || !$user->hasRole('ROLE_USER')) {
         $this->flash('error', 'You must be registered and logged in to submit a game.');
         throw new AccessDeniedException();
     }
     $game = $this->repo('EGGame')->findOneBy(['user' => $user->getId()]);
     if (!$game) {
         return $this->redirectRoute('eg_submit_gate');
     }
     /**
      * Do this somewhere else?
      */
     $guesser = MimeTypeGuesser::getInstance();
     $guesser->register(new UnityMimeTypeGuesser());
     $feedback = $this->repo('EGFeedback')->fetchFeedbackForGame($game);
     $stats = $this->repo('EGGameStats')->getOrCreate($game, date('Y-m'));
     $scholarship = $this->repo('Scholarship')->getCurrentEvoGames();
     $phase = 'qualifier';
     if ($this->repo('EGGame')->isInContest($game, $scholarship)) {
         $phase = 'contest';
     }
     $fb = $this->createFormBuilder();
     $fb->add('game', 'file', ['label' => $game->getSwfFile() == null ? 'Upload Game: ' : 'Re-upload Game: ', 'constraints' => [new NotBlank()]]);
     $form = $fb->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         $filesystem = $this->fs('game');
         $gameUploader = new GameUploader($filesystem);
         try {
             $file = $form->get('game')->getData();
             $url = $gameUploader->upload($file);
             $game->setSwfFile($url);
             switch ($file->getMimeType()) {
                 case 'application/vnd.unity':
                     $game->setType(EGGame::TYPE_UNITY);
                     break;
                 case 'application/x-shockwave-flash':
                     $game->setType(EGGame::TYPE_FLASH);
                     break;
                 default:
                     $game->setType(EGGame::TYPE_FLASH);
                     break;
             }
             $this->em()->flush();
             /**
              * TODO: Clean up old files in S3.
              */
         } catch (\InvalidArgumentException $e) {
             $this->flash('error', $e->getMessage());
             return $this->redirectRoute('eg_manage');
         }
         $this->flash('success', "Your file was uploaded successfully.");
         return $this->redirectRoute('eg_manage');
     }
     $gameParameters = [];
     $flashVars = [];
     if ($game->getSwfFile() != null) {
         // Create a play session for testing
         /** @var SecureRandomInterface $random */
         $random = $this->get('security.secure_random');
         $session = EGPlaySession::make($random, EGPlaySession::PHASE_FREEPLAY, $game, $user);
         $this->em()->persist($session);
         $this->em()->flush();
         $gameParameters = ['session_id' => $session ? $session->getId() : null, 'completion_url' => $this->generateUrl('eg_manage', [], UrlGeneratorInterface::ABSOLUTE_URL), 'api_endpoint' => (strpos($this->getRequest()->getHttpHost(), 'gotchosen.dev') === false ? 'https://' : 'http://') . $this->getRequest()->getHttpHost() . '/evolution-games/api/v1'];
         $flashVars = http_build_query(['session_id' => $gameParameters['session_id'], 'completion_url' => $gameParameters['completion_url'], 'api_endpoint' => $gameParameters['api_endpoint']]);
     }
     return ['game' => $game, 'gameStatus' => EGGame::$status_types[$game->getStatus()], 'flashVars' => $flashVars, 'gameParameters' => $gameParameters, 'monthStats' => $stats, 'feedback' => $feedback, 'phase' => $phase, 'submitRateUrl' => $this->generateUrl('eg_manage_rate_feedback'), 'form' => $form->createView()];
 }