/** * Load data fixtures with the passed EntityManager * * @param ObjectManager $manager */ function load(ObjectManager $manager) { return; $dataFile = __DIR__ . '/dump/Player.yml'; if (!file_exists($dataFile)) { throw new RuntimeException(sprintf('No file exist with fixture data on "%s" path', $dataFile)); } $dataList = Yaml::parse($dataFile); $pantheonRepo = $manager->getRepository('Erliz\\SkyforgeBundle\\Entity\\Pantheon'); $roleRepo = $manager->getRepository('Erliz\\SkyforgeBundle\\Entity\\Role'); $persistCounter = 0; foreach ($dataList as $item) { $player = new Player(); $player->setId($item['id'])->setName($item['nick'])->setNick($item['name'])->setImg($item['img'])->setCreatedAt(new \DateTime($item['created_at']))->setModifiedAt(new \DateTime($item['modified_at'])); if (!empty($item['pantheon'])) { $player->setPantheon($pantheonRepo->findOneBy(array('name' => $item['pantheon']))); } if (!empty($item['current_role'])) { $player->setCurrentRole($roleRepo->findOneBy(array('name' => $item['current_role']))); } $manager->persist($player); $persistCounter++; if ($persistCounter > 1000) { $manager->flush(); $persistCounter = 0; } } $manager->flush(); }
/** * @param string $playerId */ public function updatePlayer($playerId, $withFlush = false) { $app = $this->getApp(); /** @var EntityManager $em */ $em = $this->getEntityManager(); /** @var ParseService $parseService */ $parseService = $app['parse.skyforge.service']; $parseService->setAuthData($this->regionService->getCredentials()); /** @var Player $player */ $player = $this->playerRepo->find($playerId); try { $avatarDataTimeStart = microtime(true); $avatarData = $parseService->getDataFromProfilePage($parseService->getPage($this->makeProfileUrlByPlayerId($playerId))); $this->logger->addInfo(sprintf('Avatar data take %s sec to proceed', microtime(true) - $avatarDataTimeStart)); $statDataTimeStart = microtime(true); $statData = json_decode($parseService->getPage($this->makeStatUrlByPlayerId($playerId), true)); $this->logger->addInfo(sprintf('Stat data take %s sec to proceed', microtime(true) - $statDataTimeStart)); } catch (RuntimeException $e) { if ($e->getCode() == 403) { throw new RuntimeException(sprintf('Stat data are closed for player "%s"', $playerId), 403); } else { throw $e; } } if (!$player) { $player = new Player(); $player->setId($playerId); $em->persist($player); } $currentPantheon = null; if ($avatarData && $avatarData['pantheon_id']) { $currentPantheon = $this->pantheonRepo->find($avatarData['pantheon_id']); } $currentRole = $this->roleRepo->findOneBy(array('name' => $avatarData['role_name'])); if (empty($currentRole)) { $currentRole = $this->roleRepo->find(1); } $today = new \DateTime('-4 hour'); $shownDates = $statData->avatarStats->daysToShow; $dailyStatsLoopTimeStart = microtime(true); foreach ($statData->avatarStats->dailyStats as $key => $dayStat) { // -4 hour server update on 4 hour at night $date = new \DateTime($key - $shownDates + 1 . ' day -4 hour'); $totalTime = null; if ($key + 1 == $shownDates) { $totalTime = $statData->avatarStats->secondsPlayed; } if ($oldDateStat = $this->dateStatRepo->findOneBy(array('player' => $player->getId(), 'date' => $date))) { if ($today->format('Y-m-d') == $oldDateStat->getDate()->format('Y-m-d')) { $oldDateStat->setCurrentPrestige($avatarData['prestige']['current'])->setMaxPrestige($avatarData['prestige']['max'])->setRole($currentRole)->setPantheon($currentPantheon)->setTotalTime($totalTime); } $oldDateStat->setPveMobKills($dayStat->pveMobKills)->setPveBossKills($dayStat->pveBossKills)->setPveDeaths($dayStat->pveDeaths)->setPvpKills($dayStat->pvpKills)->setPvpDeaths($dayStat->pvpDeaths)->setPvpAssists($dayStat->pvpAssists); continue; } $player->setName($avatarData['name'])->setNick($avatarData['nick'])->setImg($avatarData['img'])->setCurrentRole($currentRole); $dateStat = new PlayerDateStat(); $dateStat->setPlayer($player)->setDate($date)->setRole($currentRole)->setPantheon($currentPantheon)->setTotalTime($totalTime)->setCurrentPrestige($avatarData['prestige']['current'])->setMaxPrestige($avatarData['prestige']['max'])->setPveMobKills($dayStat->pveMobKills)->setPveBossKills($dayStat->pveBossKills)->setPveDeaths($dayStat->pveDeaths)->setPvpKills($dayStat->pvpKills)->setPvpDeaths($dayStat->pvpDeaths)->setPvpAssists($dayStat->pvpAssists); if (isset($statData->adventureStats) && isset($statData->adventureStats->byAdventureStats)) { $dateStat->setPvpTime($this->getTimeSpentByAdventureType($statData->adventureStats->byAdventureStats, $this::PVP_TYPE)); } $em->persist($dateStat); } $this->logger->addInfo(sprintf('Daily stat take %s sec to proceed', microtime(true) - $dailyStatsLoopTimeStart)); $classStatsLoopTimeStart = microtime(true); foreach ($statData->avatarStats->classStats as $roleData) { $role = $this->roleRepo->findOneBy(array('resourceId' => $roleData->characterClass->resourceId)); if (!$role) { throw new RuntimeException('New role detected ' . json_encode($roleData->characterClass)); } $roleStat = $this->roleStatRepo->findOneBy(array('player' => $player->getId(), 'role' => $role->getId())); if (!$roleStat) { $roleStat = new PlayerRoleStat(); $roleStat->setPlayer($player)->setRole($role); $em->persist($roleStat); } $roleDataStat = $roleData->stats; $roleStat->setSecondsActivePlayed($roleData->secondsActivePlayed)->setSecondsPlayed($roleData->secondsPlayed)->setPveMobKills($roleDataStat->pveMobKills)->setPveBossKills($roleDataStat->pveBossKills)->setPveDeaths($roleDataStat->pveDeaths)->setPvpKills($roleDataStat->pvpKills)->setPvpDeaths($roleDataStat->pvpDeaths)->setPvpAssists($roleDataStat->pvpAssists); } $this->logger->addInfo(sprintf('Class stat take %s sec to proceed', microtime(true) - $classStatsLoopTimeStart)); if ($withFlush) { $flushTimeStart = microtime(true); $em->flush(); $this->logger->addInfo(sprintf('Flush db take %s sec to proceed', microtime(true) - $flushTimeStart)); } }
protected function execute(InputInterface $input, OutputInterface $output) { $app = $this->getProjectApplication(); /** @var EntityManager $em */ $em = $app['orm.em']; /** @var ParseService $parseService */ $parseService = $app['parse.skyforge.service']; $parseService->setAuthData($app['config']['skyforge']['pantheon']); /** @var PlayerRepository $playerRepository */ $playerRepository = $em->getRepository('Erliz\\SkyforgeBundle\\Entity\\Player'); $pantheonRepository = $em->getRepository('Erliz\\SkyforgeBundle\\Entity\\Pantheon'); $lockFilePath = '/home/sites/erliz.ru/app/cache/curl/parse.lock'; if (is_file($lockFilePath)) { throw new \RuntimeException('Another parse in progress'); } else { file_put_contents($lockFilePath, getmypid()); } /** @var Pantheon $pantheon */ $pantheon = $pantheonRepository->find($input->getArgument('id')); $today = new \DateTime(); $todayString = $today->format('d-m-Y'); if ($input->getOption('update-donations')) { $playersDonationInfo = $parseService->getDonationFromPantheonPage($pantheon->getId()); foreach ($playersDonationInfo as $playerId => $data) { $player = $playerRepository->find($playerId); if (!$player) { $player = new Player(); $player->setId($playerId)->setNick($data['nick'])->setName($data['name'])->setPantheon($pantheon); $em->persist($player); } if ($data['balance'] == 0) { continue; } if ($input->getOption('first-update')) { $transaction = new BillingTransaction(); $transaction->setPlayer($player)->setAction(BillingTransaction::DEPOSIT_ACTION)->setAmount($data['balance'])->setComment('First deposit'); $em->persist($transaction); $wipeTransaction = new BillingTransaction(); $wipeTransaction->setPlayer($player)->setAction(BillingTransaction::TAX_ACTION)->setAmount($data['balance'])->setComment('Wipe charity donations'); $em->persist($wipeTransaction); } else { $transactionsDepositAmount = 0; $transactionsWithdrawAmount = 0; $playerTransactions = $player->getBillingTransactions(); if (count($playerTransactions) > 0) { $deposits = $playerTransactions->filter(function ($el) { return $el->getAction() == BillingTransaction::DEPOSIT_ACTION; }); $withdraws = $playerTransactions->filter(function ($el) { return $el->getAction() == BillingTransaction::WITHDRAW_ACTION; }); /** @var BillingTransaction $deposit */ foreach ($deposits as $deposit) { $transactionsDepositAmount += $deposit->getAmount(); } /** @var BillingTransaction $withdraw */ foreach ($withdraws as $withdraw) { $transactionsWithdrawAmount -= $withdraw->getAmount(); } } $depositAmount = $data['balance'] - $transactionsDepositAmount + $transactionsWithdrawAmount; if ($depositAmount == 0) { continue; } if ($depositAmount < 0) { $maxPlayerBalance = $this->getMaxAccountBalance($playerTransactions); $leavePantheonTransaction = new BillingTransaction(); $leavePantheonTransaction->setPlayer($player)->setAction(BillingTransaction::WITHDRAW_ACTION)->setAmount($maxPlayerBalance)->setComment(sprintf('Return amount that was before pantheon leave')); $em->persist($leavePantheonTransaction); $depositAmount = $data['balance'] - $transactionsDepositAmount + $maxPlayerBalance; if ($depositAmount < 0) { $output->writeln(sprintf('<comment>Bad balance data on player %s "%s"</comment>', $playerId, $data['balance'])); continue; } } $depositTransaction = new BillingTransaction(); $depositTransaction->setPlayer($player)->setAction(BillingTransaction::DEPOSIT_ACTION)->setAmount($depositAmount)->setComment(sprintf('Deposit %s total sum %s', $todayString, $data['balance'])); $em->persist($depositTransaction); } } } if ($input->getOption('add-tax')) { $taxAmount = 82500; foreach ($pantheon->getMembers() as $player) { $transaction = new BillingTransaction(); $transaction->setPlayer($player)->setAction(BillingTransaction::TAX_ACTION)->setAmount($taxAmount)->setComment('Tax pay for ' . $todayString); $em->persist($transaction); } } $em->flush(); unlink($lockFilePath); }
/** * @param CommunityInterface $community * @param OutputInterface $output * @param string $type */ private function updateCommunityMembers(CommunityInterface $community, OutputInterface $output, $type) { $this->logger->addInfo(sprintf('Checking %s "%s" with %s', $type, $community->getName(), $community->getId())); $members = array(); try { for ($page = 1; $page <= 20; $page++) { if ($this->regionService->getRegion() == RegionService::RU_REGION) { $responseMessage = $this->parseService->getPage($this->makeCommunityMembersMoreUrl($community->getId()), true, $this->makeCommunityMembersUrl($community->getId()), array('t:zone' => 'bunchZone', 'bunchIndex' => $page)); $response = json_decode($responseMessage); } else { $response = $this->parseService->getPage($this->makeCommunityMembersUrl($community->getId()) . '?page=' . $page, false, $this->makeCommunityMembersUrl($community->getId())); } if (!$response) { $this->logger->addInfo(sprintf('Empty page %s', $page)); break; } if ($this->regionService->getRegion() == RegionService::RU_REGION) { $pageMembers = $this->parseService->getMembersFromCommunityPage($response->content); } else { $pageMembers = $this->parseService->getMembersFromCommunityPage($response); } $this->logger->addInfo(sprintf('Page %s parsed successful, get %s members', $page, count($pageMembers))); $members = $members + $pageMembers; usleep(rand(500, 1500) * 1000); } } catch (RuntimeException $e) { $this->logger->addInfo('Exception: ' . $e->getMessage() . ' ' . $e->getCode()); } if ($type == $this::TYPE_PANTHEON) { $dbMembers = $this->playerRepository->findBy(array('pantheon' => $community->getId())); } elseif ($type == $this::TYPE_COMMUNITY) { $dbMembers = $this->playerRepository->findByCommunity($community); } else { throw new \InvalidArgumentException(sprintf('Unknown community type "%s" to find members', $type)); } /** @var Player $member */ foreach ($dbMembers as $member) { if ($type == $this::TYPE_PANTHEON) { $member->removePantheon(); } elseif ($type == $this::TYPE_COMMUNITY) { $member->getCommunities()->removeElement($community); } else { throw new \InvalidArgumentException(sprintf('Unknown community type "%s" to remove community', $type)); } } foreach ($members as $parsedMember) { $player = $this->playerRepository->find($parsedMember->id); if (!$player) { $player = new Player(); $player->setId($parsedMember->id); $this->em->persist($player); } if ($parsedMember->name) { $player->setName($parsedMember->name); } if ($parsedMember->nick) { $player->setNick($parsedMember->nick); } else { $player->setNick(''); } $community->addMember($player); if ($type == $this::TYPE_PANTHEON) { $player->setPantheon($community); } elseif ($type == $this::TYPE_COMMUNITY) { $player->getCommunities()->add($community); } else { throw new \InvalidArgumentException(sprintf('Unknown community type "%s" to add for member', $type)); } } $community->setUpdatedAt(new DateTime()); usleep(rand(500, 1500) * 1000); }