/**
  * @param $data
  * @return AbstractDefaultTypedAddress
  */
 protected function createAddress($data)
 {
     /** @var Country $country */
     $country = $this->countryRepository->findOneBy(['iso2Code' => $data['country']]);
     if (!$country) {
         throw new \RuntimeException('Can\'t find country with ISO ' . $data['country']);
     }
     /** @var Region $region */
     $region = $this->regionRepository->findOneBy(['country' => $country, 'code' => $data['state']]);
     if (!$region) {
         throw new \RuntimeException(printf('Can\'t find region with country ISO %s and code %s', $data['country'], $data['state']));
     }
     $types = [];
     $typesFromData = explode(',', $data['types']);
     foreach ($typesFromData as $type) {
         $types[] = $this->addressTypeRepository->find($type);
     }
     $defaultTypes = [];
     $defaultTypesFromData = explode(',', $data['defaultTypes']);
     foreach ($defaultTypesFromData as $defaultType) {
         $defaultTypes[] = $this->addressTypeRepository->find($defaultType);
     }
     $address = $this->getNewAddressEntity();
     $address->setTypes(new ArrayCollection($types));
     $address->setDefaults(new ArrayCollection($defaultTypes))->setPrimary(true)->setLabel('Primary address')->setCountry($country)->setStreet($data['street'])->setCity($data['city'])->setRegion($region)->setPostalCode($data['zipCode']);
     return $address;
 }
 /**
  * Attempts to authenticate a GrantToken
  *
  * @param GrantToken $token
  *
  * @return GrantToken
  *
  * @throws AuthenticationException
  */
 public function authenticate(TokenInterface $token)
 {
     $credentials = $token->getCredentials();
     $clientId = $credentials['client_id'];
     /** @var ClientInterface $client */
     $client = $this->clientRepository->find($clientId);
     // Verify client id
     if (!$client) {
         throw new AuthenticationException("Client with id {$clientId} does not exist");
     }
     // Verify client secret
     $clientSecret = $credentials['client_secret'];
     if (!$client->getSecret() === $clientSecret) {
         throw new AuthenticationException("Invalid client secret");
     }
     // Verify grant type
     if (!in_array($token->getGrantType(), $client->getAllowedGrantTypes())) {
         throw new AuthenticationException("Grant type not allowed");
     }
     // Verify refresh_token
     $refreshToken = $this->refreshTokenRepository->findOneBy(["token" => $credentials['refresh_token'], "client" => $client]);
     if ($refreshToken === null) {
         throw new AuthenticationException("Invalid token");
     }
     // Verify expiry date
     if ($refreshToken->isExpired()) {
         throw new AuthenticationException("Token has expired");
     }
     $user = $refreshToken->getUser();
     $token->setUser($user);
     $token->setClient($client);
     return $token;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $app = $this->getProjectApplication();
     $this->logger = $this->getLogger();
     $this->regionService = $app['region.skyforge.service'];
     $this->regionService->setRegion($input->getOption('region'));
     $this->em = $app['orm.ems'][$this->regionService->getDbConnectionNameByRegion()];
     $this->parseService = $app['parse.skyforge.service'];
     $this->parseService->setAuthData($this->regionService->getCredentials());
     $this->playerRepository = $this->em->getRepository('Erliz\\SkyforgeBundle\\Entity\\Player');
     $this->pantheonRepository = $this->em->getRepository('Erliz\\SkyforgeBundle\\Entity\\Pantheon');
     $this->communityRepository = $this->em->getRepository('Erliz\\SkyforgeBundle\\Entity\\Community');
     //        $lockFilePath = $app['config']['app']['path'].'/cache/curl/parse.lock';
     //        if (is_file($lockFilePath)) {
     //            throw new \RuntimeException('Another parse in progress');
     //        } else {
     //            file_put_contents($lockFilePath, getmypid());
     //        }
     if ($communityId = $input->getOption('id')) {
         $community = $this->communityRepository->find($communityId);
         $type = $this::TYPE_COMMUNITY;
         if (!$community) {
             $community = $this->pantheonRepository->find($communityId);
             $type = $this::TYPE_PANTHEON;
         }
         if (!$community) {
             $this->logger->addInfo(sprintf('Community with id %s not found in db', $communityId));
         } else {
             $this->updateCommunityMembers($community, $output, $type);
             $this->flush();
         }
     }
     if ($input->getOption('pantheons') || $input->getOption('communities')) {
         $lastId = $input->getOption('lastId');
         if ($input->getOption('pantheons')) {
             $sqlResponse = $this->em->createQuery("\n                    SELECT pt.id, count(pl.id) cnt\n                    FROM Erliz\\SkyforgeBundle\\Entity\\Pantheon pt\n                    LEFT JOIN pt.members pl\n                    group by pt.id\n                    order by cnt DESC")->getScalarResult();
             $type = $this::TYPE_PANTHEON;
             $repo = $this->pantheonRepository;
         } else {
             $sqlResponse = $this->em->createQuery("\n                    SELECT pt.id, count(pl.id) cnt\n                    FROM Erliz\\SkyforgeBundle\\Entity\\Community pt\n                    JOIN pt.members pl\n                    group by pt.id\n                    order by cnt DESC")->getScalarResult();
             $type = $this::TYPE_COMMUNITY;
             $repo = $this->communityRepository;
         }
         $communityIds = array_map('current', $sqlResponse);
         $communitiesCount = count($communityIds);
         /** @var CommunityInterface $community */
         foreach ($communityIds as $index => $communityId) {
             if ($communityId == $lastId) {
                 $lastId = false;
             }
             if ($lastId) {
                 continue;
             }
             $this->updateCommunityMembers($repo->find($communityId), $output, $type);
             $this->logger->addInfo(sprintf('Processed %s / %s', $index + 1, $communitiesCount));
             $this->flush();
         }
     }
     //        unlink($lockFilePath);
 }
 /**
  * Attempts to authenticate a GrantToken
  *
  * @param GrantToken $token
  *
  * @return GrantToken
  *
  * @throws AuthenticationException
  */
 public function authenticate(TokenInterface $token)
 {
     $credentials = $token->getCredentials();
     $clientId = $credentials['client_id'];
     /** @var ClientInterface $client */
     $client = $this->clientRepository->find($clientId);
     // Verify client id
     if (!$client) {
         throw new AuthenticationException("Client with id {$clientId} does not exist");
     }
     // Verify client secret
     $clientSecret = $credentials['client_secret'];
     if (!$client->getSecret() === $clientSecret) {
         throw new AuthenticationException("Invalid client secret");
     }
     // Verify grant type
     if (!in_array($token->getGrantType(), $client->getAllowedGrantTypes())) {
         throw new AuthenticationException("Grant type not allowed");
     }
     if ($client->getUser() === null) {
         throw new AuthenticationException("Client is not associated with any user");
     }
     $token->setUser($client->getUser());
     $token->setClient($client);
     return $token;
 }
 /**
  * @param int $id
  *
  * @return bool|Pantheon
  */
 public function getById($id)
 {
     $pantheon = $this->repository->find($id);
     if (!$pantheon) {
         throw new \InvalidArgumentException(sprintf('Pantheon with id "%s" not found', $id));
     }
     return $pantheon;
 }
 public function findById($id)
 {
     $sheet = $this->doctrineSheetRepo->find($id);
     if (!$sheet instanceof QuestionSheet) {
         throw new \InvalidArgumentException("Unable to fetch this sheet");
     }
     return $sheet;
 }
 public function findById($id)
 {
     $foundUser = $this->doctrineUserRepo->find($id);
     if (null === $foundUser) {
         throw new \InvalidArgumentException("user not found");
     }
     return $foundUser;
 }
Example #8
0
 public function find($id)
 {
     $event = $this->repo->find($id);
     if (null === $event) {
         throw new NotFoundHttpException(sprintf("Couldn't find event with id '%d'", $id));
     }
     return $event;
 }
Example #9
0
 public function find($id)
 {
     $calendar = $this->repo->find($id);
     if (null === $calendar) {
         throw new NotFoundHttpException(sprintf("Couldn't find calendar with id '%d'", $id));
     }
     return $calendar;
 }
 public function find($id)
 {
     $entity = $this->entityRepository->find($id);
     if (!$entity) {
         throw new MissingEntityException();
     }
     return $entity;
 }
Example #11
0
 public function onLoggedOut(Security $security)
 {
     // BUG: Nette\Security\User 2.1 fires onLoggedOut before clearing storage
     if ($user = $this->repository->find($security->getIdentity()->getId())) {
         $security->getStorage()->setAuthenticated(FALSE);
         $this->user->signOut($user);
     }
 }
 /**
  * @param $id
  * @return \Delivery\Entity\User
  */
 public function findUser($id)
 {
     if ($this->cache->has($id)) {
         $entity = $this->cache->get($id);
     } else {
         $entity = $this->repository->find($id);
     }
     return $entity;
 }
Example #13
0
 function defaultAction($id)
 {
     /** @var Page $page */
     $page = $this->pageRepository->find($id);
     if (!$page) {
         throw new NotFoundHttpException();
     }
     $content = $this->templating->render('Page\\default.twig', array('title' => $page->getTitle(), 'content' => $page->getContent()));
     return new Response($content);
 }
 /**
  * Transforms an id to an entity.
  *
  * @param  string $id
  *
  * @return mixed
  *
  * @throws TransformationFailedException if entiyt is not found.
  */
 public function reverseTransform($id)
 {
     if (!$id) {
         return null;
     }
     $entity = $this->repository->find($id);
     if (null === $entity) {
         throw new TransformationFailedException(sprintf('A %s with id "%s" does not exist!', $this->entityName, $id));
     }
     return $entity;
 }
Example #15
0
 /**
  * @param mixed $value
  *
  * @throws BadRequestException
  *
  * @return object
  */
 public function filterIn($value)
 {
     if (!is_object($value)) {
         $entity = $this->repository->find($value);
     } elseif ($value instanceof QueryInterface) {
         $entity = $value->getEntity($this->repository);
     }
     $class = $this->repository->getClassName();
     if (!$entity instanceof $class) {
         throw new BadRequestException('Desired entity of type \'' . $this->repository->getClassName() . '\' could not be found.');
     }
     return $entity;
 }
Example #16
0
 /**
  * {@inheritDoc}
  */
 public function read()
 {
     $identity = $this->storage->read();
     if ($identity) {
         try {
             return $this->repository->find($identity);
         } catch (DBALException $e) {
             // The user table does not exist.
             return null;
         }
     }
     return null;
 }
Example #17
0
 /**
  * Creates a new project from an existing template
  * 
  * @return ProjectManager
  */
 public function createProjectFromTemplate(Project $project)
 {
     // copy from this template
     $template = $this->repo->find($project->getCopiedFrom());
     $this->em->persist($project);
     // copy phases from template
     foreach ($template->getPhases() as $tplPhase) {
         $phase = new Phase();
         $phase->copyFrom($tplPhase)->setProject($project);
         $this->em->persist($phase);
     }
     $this->em->flush();
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function get($mediaId, $formatKey)
 {
     if (!isset($this->formats[$formatKey])) {
         throw new FormatNotFoundException($formatKey);
     }
     $media = $this->mediaManager->getEntityById($mediaId);
     $fileVersion = $this->getFileVersionForMedia($media);
     /** @var FormatOptions $formatOptions */
     $formatOptions = $this->formatOptionsRepository->find(['fileVersion' => $fileVersion, 'formatKey' => $formatKey]);
     if (!isset($formatOptions)) {
         return [];
     }
     return $this->entityToArray($formatOptions);
 }
Example #19
0
 /**
  * @param EntityRepository $repository
  * @param $type
  * @return \Erik\UserBundle\Entity\Role
  * @throws Exception
  */
 private function getRole(EntityRepository $repository, $type)
 {
     switch ($type) {
         case "company":
             $role = $repository->find(Role::ROLE_COMPANY);
             break;
         case "user":
             $role = $repository->find(Role::ROLE_USER);
             break;
         default:
             throw new Exception($this->get("translator")->trans("you.have.no.permission"), 404, null);
     }
     return $role;
 }
Example #20
0
 /**
  * {@inheritDoc}
  */
 public function authenticate()
 {
     $key = $this->repository->find($this->getIdentity());
     if (!$key || !$key->getOwner()->isActive()) {
         return new Result(Result::FAILURE_IDENTITY_NOT_FOUND, null, ['Key identity not found.']);
     }
     if (!$key->verifyCredential($this->getCredential())) {
         return new Result(Result::FAILURE_CREDENTIAL_INVALID, null, ['Invalid key credential.']);
     }
     // Update the last IP address and datetime accessed.
     $key->setLastIp($_SERVER['REMOTE_ADDR']);
     $key->setLastAccessed(new DateTime());
     $this->getEntityManager()->flush();
     return new Result(Result::SUCCESS, $key->getOwner());
 }
 /**
  * Create the Category by hand. The method ->fromArray do not work
  *
  * @param int $id
  * @return null|Category
  */
 private function findCategoryById($id)
 {
     if (null === $id) {
         return null;
     }
     return $this->repository->find($id);
 }
 /**
  * @param OutputInterface $output
  */
 private function findCommunities(OutputInterface $output)
 {
     $this->logger->addInfo('Finding new communities');
     $communities = array();
     try {
         for ($page = 1; $page <= 20; $page++) {
             $responseMessage = $this->parseService->getPage($this->makeCommunitiesMoreUrl(), true, $this->makeCommunitiesUrl(), array('t:zone' => 'bunchZone', 'bunchIndex' => $page));
             $response = json_decode($responseMessage);
             if (!$response) {
                 $this->logger->addInfo(sprintf('Empty page %s', $page));
                 break;
             }
             $pageCommunities = $this->parseService->getCommunities($response->content);
             $this->logger->addInfo(sprintf('Page %s parsed successful, get %s communities', $page, count($pageCommunities)));
             $communities = $communities + $pageCommunities;
             usleep(rand(500, 1500) * 1000);
         }
     } catch (RuntimeException $e) {
         $this->logger->addInfo('Exception: ' . $e->getMessage() . ' ' . $e->getCode());
     }
     foreach ($communities as $parsedCommunity) {
         $community = $this->pantheonRepository->find($parsedCommunity->id);
         if ($community) {
             continue;
         }
         $community = new Pantheon();
         $community->setId($parsedCommunity->id)->setImg($parsedCommunity->pic)->setName($parsedCommunity->name)->setIsActive(0)->setUpdatedAt(new DateTime());
         $this->em->persist($community);
     }
     $this->em->flush();
 }
Example #23
0
 /**
  * @param User $user
  * @param PageAnimal $pageAnimal
  * @throws HistoryException
  * @throws ValidationException
  */
 public function commit(User $user, PageAnimal $pageAnimal)
 {
     /** @var PageAnimalBranch $pageAnimalBranch */
     $pageAnimalBranch = $this->pageAnimalBranchRepository->find($pageAnimal->getId());
     if ($pageAnimalBranch == null) {
         throw new HistoryException(HistoryException::BRANCHE_INCONNUE);
     }
     if ($user->getId() !== $pageAnimalBranch->getOwner()->getId()) {
         throw new HistoryException(HistoryException::DROIT_REFUSE);
     }
     /** @var PageAnimalCommit $clientHead */
     $clientHead = $this->pageAnimalCommitRepository->find($pageAnimal->getHead());
     if ($clientHead->getId() !== $pageAnimalBranch->getCommit()->getId()) {
         throw new HistoryException(HistoryException::NON_FAST_FORWARD);
     }
     if (empty($pageAnimal->getNom())) {
         throw new ValidationException(ValidationException::EMPTY_NOM);
     }
     if (empty($pageAnimal->getDateNaissance())) {
         throw new ValidationException(ValidationException::EMPTY_DATE_NAISSANCE);
     }
     $commit = new PageAnimalCommit($clientHead, $pageAnimal->getNom(), $pageAnimal->getDateNaissance(), $pageAnimal->getDescription(), $pageAnimal->getStatut(), $pageAnimal->getSexe(), $pageAnimal->getPhotos());
     $this->doctrine->persist($commit);
     $pageAnimalBranch->setCommit($commit);
     $this->doctrine->flush([$commit, $pageAnimalBranch]);
     $pageAnimal->setHead($commit->getId());
 }
Example #24
0
 public function delete()
 {
     /** @var EntityRepository $entity */
     $entity = $this->nanoEntity->find($this->getIdFromRequest());
     $this->getEntityManager()->remove($entity);
     $this->getEntityManager()->flush();
 }
Example #25
0
 /**
  * {@inheritdoc}
  *
  * @throws EntityNotFoundException
  */
 public function find($id, $lockMode = null, $lockVersion = null)
 {
     /** @var EntityInterface $entity */
     $entity = parent::find($id, $lockMode, $lockVersion);
     $this->throwExceptionIfNoEntity($entity);
     return $entity;
 }
 /**
  * Overrides find() accepting either id or slug.
  *
  * (non-PHPdoc)
  * @see \Doctrine\ORM\EntityRepository::find()
  */
 public function find($id, $lockMode = LockMode::NONE, $lockVersion = null)
 {
     if (is_numeric($id)) {
         return parent::find($id, $lockMode, $lockVersion);
     }
     return $this->findOneBy(array('slug' => $id));
 }
Example #27
0
 /**
  * @param int  $id
  * @param bool $exception
  *
  * @return mixed
  *
  * @throws NotFoundHttpException
  */
 public function find($id, $exception = false)
 {
     $entity = $this->repository->find($id);
     if ($exception && !$entity) {
         throw new NotFoundHttpException('Unable to find entity.');
     }
     return $entity;
 }
Example #28
0
 function it_handles_a_find_query(Find $query, EntityRepository $repository, EntityManagerInterface $em)
 {
     $query->getEntityClass()->willReturn('Indigo\\Crud\\Stub\\Entity');
     $query->getId()->willReturn(1);
     $repository->find(1)->shouldBeCalled();
     $em->getRepository('Indigo\\Crud\\Stub\\Entity')->willReturn($repository);
     $this->handle($query);
 }
Example #29
0
 /**
  * Finds an entity by its primary key / identifier.
  *
  * @param mixed $id The identifier.
  * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
  *                              or NULL if no specific lock mode should be used
  *                              during the search.
  * @param int|null $lockVersion The lock version.
  *
  * @return Game
  * @throws GameNotFoundException
  */
 public function find($id, $lockMode = null, $lockVersion = null) : Game
 {
     $game = parent::find($id, $lockMode, $lockVersion);
     if (!$game instanceof Game) {
         throw new GameNotFoundException();
     }
     return $game;
 }
Example #30
0
 public function find($id, $lockMode = LockMode::NONE, $lockVersion = null)
 {
     $channel = parent::find($id, $lockMode = LockMode::NONE, $lockVersion = null);
     if (is_null($channel)) {
         $channel = $this->findBySlug($id);
     }
     return $channel;
 }