/**
  * @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;
 }
 private function uniqueAppKey()
 {
     do {
         $appKey = str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
         $application = $this->userRepository->findBy(array('appKey' => $appKey));
     } while ($application);
     return $appKey;
 }
 /**
  * Return a similar articles by category
  * @param Article $article
  * @return Article array
  */
 public function getSimilarArticlesByCategory(Article $article)
 {
     $category = $article->getCategory();
     $similarArticles = $this->articleRepository->findBy(array('category' => $category), array('date' => 'ASC'), 3);
     unset($similarArticles[array_search($article, $similarArticles)]);
     return $similarArticles;
 }
Beispiel #4
3
 /**
  * @inheritdoc
  */
 public function validateAttribute($model, $attribute)
 {
     $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
     $findResult = $this->repository->findOneBy([$targetAttribute => $model->{$attribute}]);
     if ($findResult === null) {
         $this->addError($model, $attribute, $this->message);
     }
 }
 /**
  * @test
  * @covers Plum\PlumDoctrine\ORM\RepositoryReader::count()
  */
 public function countShouldReturnNumberOfResults()
 {
     $result = new stdClass();
     $this->repository->shouldReceive('findBy')->andReturn([$result, $result]);
     $reader = new RepositoryReader($this->repository, ['age' => 29]);
     $this->assertEquals(2, $reader->count());
 }
Beispiel #6
0
 public function load(ObjectManager $manager)
 {
     $organization = $this->getReference('default_organization');
     /** @var \Oro\Bundle\UserBundle\Entity\Role $marketingRole */
     $marketingRole = $this->roles->findOneBy(array('role' => 'ROLE_MARKETING_MANAGER'));
     /** @var \Oro\Bundle\UserBundle\Entity\Role $saleRole */
     $saleRole = $this->roles->findOneBy(array('role' => LoadRolesData::ROLE_MANAGER));
     /** @var \Oro\Bundle\UserBundle\Entity\Group $salesGroup */
     $salesGroup = $this->group->findOneBy(array('name' => 'Executive Sales'));
     /** @var \Oro\Bundle\UserBundle\Entity\Group $marketingGroup */
     $marketingGroup = $this->group->findOneBy(array('name' => 'Executive Marketing'));
     /** @var \Oro\Bundle\UserBundle\Entity\UserManager $userManager */
     $userManager = $this->container->get('oro_user.manager');
     $sale = $userManager->createUser();
     $sale->setUsername('sale')->setPlainPassword('sale')->setFirstName('Ellen')->setLastName('Rowell')->addRole($saleRole)->addGroup($salesGroup)->setEmail('*****@*****.**')->setOrganization($organization)->addOrganization($organization)->setBusinessUnits(new ArrayCollection(array($this->getBusinessUnit($manager, 'Acme, General'), $this->getBusinessUnit($manager, 'Acme, East'), $this->getBusinessUnit($manager, 'Acme, West'))));
     if ($this->hasReference('default_main_business')) {
         $sale->setOwner($this->getBusinessUnit($manager, 'Acme, General'));
     }
     $this->addReference('default_sale', $sale);
     $userManager->updateUser($sale);
     /** @var \Oro\Bundle\UserBundle\Entity\User $marketing */
     $marketing = $userManager->createUser();
     $marketing->setUsername('marketing')->setPlainPassword('marketing')->setFirstName('Michael')->setLastName('Buckley')->addRole($marketingRole)->addGroup($marketingGroup)->setEmail('*****@*****.**')->setOrganization($organization)->addOrganization($organization)->setBusinessUnits(new ArrayCollection(array($this->getBusinessUnit($manager, 'Acme, General'), $this->getBusinessUnit($manager, 'Acme, East'), $this->getBusinessUnit($manager, 'Acme, West'))));
     if ($this->hasReference('default_main_business')) {
         $marketing->setOwner($this->getBusinessUnit($manager, 'Acme, General'));
     }
     $this->addReference('default_marketing', $marketing);
     $userManager->updateUser($marketing);
 }
 /**
  * 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;
 }
Beispiel #8
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     /** @var Organization $organization */
     $organization = $this->organizationRepository->getFirst();
     $this->addReference('default_organization', $organization);
     /** @var BusinessUnit $oroMain */
     $oroMain = $this->businessUnitRepository->findOneBy(array('name' => 'Main'));
     if (!$oroMain) {
         $oroMain = $this->businessUnitRepository->findOneBy(array('name' => 'Acme, General'));
     }
     if (!$oroMain) {
         throw new \Exception('"Main" business unit is not defined');
     }
     $oroMain->setName('Acme, General');
     $oroMain->setEmail('*****@*****.**');
     $oroMain->setPhone('798-682-5917');
     $this->persistAndFlush($this->organizationManager, $oroMain);
     $this->addReference('default_main_business', $oroMain);
     /** @var BusinessUnit $oroUnit */
     $oroUnit = new BusinessUnit();
     /** @var BusinessUnit $mageCoreUnit */
     $mageCoreUnit = new BusinessUnit();
     $oroUnit->setName('Acme, West')->setWebsite('http://www.orocrm.com')->setOrganization($organization)->setEmail('*****@*****.**')->setPhone('798-682-5918')->setOwner($oroMain);
     $this->persist($this->organizationManager, $oroUnit);
     $this->addReference('default_crm_business', $oroUnit);
     $mageCoreUnit->setName('Acme, East')->setWebsite('http://www.magecore.com/')->setOrganization($organization)->setEmail('*****@*****.**')->setPhone('798-682-5919')->setOwner($oroMain);
     $this->persistAndFlush($this->organizationManager, $mageCoreUnit);
     $this->addReference('default_core_business', $mageCoreUnit);
 }
 /**
  * Get the attribute collection
  *
  * @return JsonResponse
  */
 public function indexAction()
 {
     $attributes = $this->attributeRepository->findAll();
     $filteredAttributes = $this->collectionFilter->filterCollection($attributes, 'pim.internal_api.attribute.view');
     $normalizedAttributes = $this->normalizer->normalize($filteredAttributes, 'internal_api');
     return new JsonResponse($normalizedAttributes);
 }
 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);
 }
 protected function givenDatabaseIsClear()
 {
     if (0 !== count($this->items->findAll())) {
         $purger = new ORMPurger($this->entityManager);
         $purger->purge();
     }
 }
 /**
  * @param EmailCampaign $emailCampaign
  * @param Campaign $campaign
  * @param bool $expected
  * @dataProvider staticCampaignProvider
  */
 public function testIsApplicableOnEmailCampaign($emailCampaign, $campaign, $expected)
 {
     $this->entityRepository->expects($this->any())->method('findOneBy')->will($this->returnValue($campaign));
     $this->managerRegistry->expects($this->any())->method('getManager')->will($this->returnValue($this->entityManager));
     $this->entityManager->expects($this->any())->method('getRepository')->will($this->returnValue($this->entityRepository));
     $this->assertEquals($expected, $this->placeholderFilter->isApplicableOnEmailCampaign($emailCampaign));
 }
 /**
  * @return QueryBuilder
  */
 private function buildBaseQuery()
 {
     $qb = $this->entityRepository->createQueryBuilder('z');
     GathererHelper::addFiltersDataToQuery($this->filters, $qb);
     GathererHelper::addAdditionalFilterDataToQuery($this->additionalFilters, $qb);
     return $qb;
 }
 /**
  * {@inheritdoc}
  */
 public function getFormValue(array $converterAttributes, $value)
 {
     if ($value === null) {
         return $this->businessUnitRepository->findAll();
     }
     return parent::getFormValue($converterAttributes, $value);
 }
 /**
  * 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 QueryBuilder $qb
  * @param string       $orderStatus
  */
 protected function addFilterByOrderStatus(QueryBuilder $qb, $orderStatus)
 {
     $aliases = $qb->getRootAliases();
     $subQueryBuilder = $this->customerRepository->createQueryBuilder('c');
     $subQueryBuilder->select('IDENTITY(c.account)')->join('c.orders', 'o', 'WITH', $subQueryBuilder->expr()->eq($subQueryBuilder->expr()->lower('o.status'), ':filteredOrderStatus'));
     $qb->andWhere($qb->expr()->in($aliases[0] . '.account', $subQueryBuilder->getDQL()))->setParameter('filteredOrderStatus', $orderStatus);
 }
 function it_handles_a_find_all_query(FindAll $query, EntityRepository $repository, EntityManagerInterface $em)
 {
     $query->getEntityClass()->willReturn('Indigo\\Crud\\Stub\\Entity');
     $repository->findAll()->shouldBeCalled();
     $em->getRepository('Indigo\\Crud\\Stub\\Entity')->willReturn($repository);
     $this->handle($query);
 }
Beispiel #18
0
 public function getNewInstance()
 {
     $instance = parent::getNewInstance();
     /* @var $instance Employee */
     $instance->getProjects()->add($this->projectRepo->findOneBy(['isInternal' => true]));
     return $instance;
 }
 /**
  * @param $deviceToken
  * @return null|int
  */
 public function findUserByDeviceToken($deviceToken)
 {
     if (null !== ($device = $this->repository->findOneBy(['deviceToken' => $deviceToken]))) {
         return $device->getUserId();
     }
     return null;
 }
Beispiel #20
0
 /**
  * {@inheritDoc}
  */
 public function findPostsByTopic(TopicInterface $topic, $page = 1)
 {
     $qb = $this->repository->createQueryBuilder('p')->select('p, t, u')->join('p.topic', 't')->join('p.user', 'u')->where('t.id = :topic')->andWhere('p.isDeleted = 0')->orderBy('p.created', 'asc')->setParameter('topic', $topic->getId());
     $pager = new Pager(new ProxyQuery($qb));
     $pager->setLimit(25)->setPage($page);
     return $pager;
 }
Beispiel #21
0
 /**
  * {@inheritDoc}
  */
 public function findTopicsByCategory(CategoryInterface $category, $page = 0)
 {
     $qb = $this->repository->createQueryBuilder('t')->select('t, c, u')->join('t.category', 'c')->join('t.user', 'u')->where('c.id = :category')->andWhere('t.isDeleted = 0')->orderBy('t.lastPost', 'desc')->setParameter('category', $category->getId());
     $pager = new Pager(new ProxyQuery($qb));
     $pager->setPage($page);
     return $pager;
 }
 protected function createTicket($iterator, $reporter, $assignee)
 {
     /** @var \Diamante\DeskBundle\Entity\Branch $branch */
     $branch = $this->branchRepository->findOneBy(array('name' => 'branchName' . $iterator));
     $ticket = new Ticket(UniqueId::generate(), new TicketSequenceNumber(null), 'ticketSubject' . $iterator, 'ticketDescription' . $iterator, $branch, $reporter, $assignee, new Source(Source::PHONE), new Priority(Priority::PRIORITY_MEDIUM), new Status(Status::OPEN));
     return $ticket;
 }
Beispiel #23
0
 function it_returns_null_when_no_entity_found(Load $query, EntityRepository $repository, EntityManagerInterface $em)
 {
     $query->getEntityClass()->willReturn('Indigo\\Crud\\Stub\\Entity');
     $query->getId()->willReturn(1);
     $repository->find(1)->willReturn(null);
     $em->getRepository('Indigo\\Crud\\Stub\\Entity')->willReturn($repository);
     $this->handle($query)->shouldReturn(null);
 }
Beispiel #24
0
 /**
  * {@inheritdoc}
  */
 public function findTextBySlugAndLocale($slug, $locale)
 {
     $qb = $this->repository->createQueryBuilder('text');
     $qb->innerJoin('text.translations', 'translation', Join::WITH, $qb->expr()->eq('translation.lang', ':locale'))->setParameter('locale', $locale);
     $qb->andWhere($qb->expr()->eq('text.slug', ':slug'))->setParameter('slug', $slug);
     $qb->select('text, translation');
     return $qb->getQuery()->getOneOrNullResult();
 }
Beispiel #25
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 string $repositoryName
  */
 protected function mockRepository($repositoryName)
 {
     $this->repository = \Mockery::mock($repositoryName)->shouldDeferMissing()->shouldAllowMockingProtectedMethods();
     $this->mockRepositoryCommands();
     $this->repository->shouldReceive('getRepository')->andReturnSelf();
     $this->repository->shouldReceive('getEntityManager')->withNoArgs()->andReturnSelf();
     $this->repository->shouldReceive('createQuery')->withAnyArgs()->andReturnSelf();
 }
 /**
  * Get a single variant group
  *
  * @param int $identifier
  *
  * @return JsonResponse
  */
 public function getAction($identifier)
 {
     $variantGroup = $this->variantGroupRepo->findOneByCode($identifier);
     if (!$variantGroup) {
         throw new NotFoundHttpException(sprintf('Variant group with code "%s" not found', $identifier));
     }
     return new JsonResponse($this->normalizer->normalize($variantGroup, 'internal_api', ['with_variant_group_values' => true]));
 }
 /**
  * @return \Generator
  */
 private function getEmoteGenerator()
 {
     /** @var Emote[] $emotes */
     $emotes = $this->entityRepository->findAll();
     foreach ($emotes as $emote) {
         (yield $emote);
     }
 }
 /** @test */
 public function getIdentity_shouldReturnTheUserCorrespondingToTheAccessToken_inQuery()
 {
     $this->oauthRequest->query['access_token'] = 'at123';
     $this->oauthServer->shouldReceive('getAccessTokenData')->with($this->oauthRequest)->andReturn(['user_id' => 'jimmy']);
     $identity = M::mock('\\Aeris\\ZfAuth\\Identity\\IdentityInterface');
     $this->identityRepository->shouldReceive('findByUsername')->with('jimmy')->andReturn($identity);
     $this->assertSame($identity, $this->identityProvider->getIdentity());
 }
 /**
  * @param null|StaticSegment $staticSegment
  * @param bool $expected
  * @dataProvider staticSegmentDataProvider
  */
 public function testIsApplicableOnMarketingList($staticSegment, $expected)
 {
     $this->entityRepository->expects($this->once())->method('findOneBy')->will($this->returnValue($staticSegment));
     $this->managerRegistry->expects($this->once())->method('getManager')->will($this->returnValue($this->entityManager));
     $this->entityManager->expects($this->once())->method('getRepository')->will($this->returnValue($this->entityRepository));
     $entity = new MarketingList();
     $this->assertEquals($expected, $this->placeholderFilter->isApplicableOnMarketingList($entity));
 }