/** * @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; }
/** * @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); } }
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; }
/** * {@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); }
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; }
/** * @param $deviceToken * @return null|int */ public function findUserByDeviceToken($deviceToken) { if (null !== ($device = $this->repository->findOneBy(['deviceToken' => $deviceToken]))) { return $device->getUserId(); } return null; }
public function getNewInstance() { $instance = parent::getNewInstance(); /* @var $instance Employee */ $instance->getProjects()->add($this->projectRepo->findOneBy(['isInternal' => true])); return $instance; }
/** * @return User * @throws InvalidArgumentException if no user is found */ public function findByOAuthResponse(UserResponseInterface $oAuthResponse) { $foundUser = $this->doctrineUserRepo->findOneBy(['oAuthProviderClass' => get_class($oAuthResponse->getResourceOwner()), 'oAuthId' => $oAuthResponse->getUsername()]); if (null === $foundUser) { throw new \InvalidArgumentException("user not found"); } return $foundUser; }
protected function findItemByName($name) { $item = $this->items->findOneBy(['name' => $name]); if (null === $item) { throw new \InvalidArgumentException(sprintf('Item with name %s does not exist.', $name)); } return $item; }
/** * @param InvitationInterface $invitation * * @return \Tahoe\Bundle\MultiTenancyBundle\Entity\TenantUser */ public function acceptInvitation(InvitationInterface $invitation) { $user = $this->userRepository->findOneBy(array('emailCanonical' => $invitation->getEmail())); $tenant = $invitation->getTenant(); $tenantUser = $this->tenantUserHandler->addUserToTenant($user, $tenant); $this->entityManager->flush(); $this->delete($invitation, true); return $tenantUser; }
/** * @param string $name * @param bool $controlledByAI * * @return Player * @throws PlayerException */ protected function createOnRequest(string $name, bool $controlledByAI) : Player { /** @var Player $player */ $player = $this->repository->findOneBy(['name' => $name]); if (null !== $player && $controlledByAI !== static::isAIControlled($player)) { throw new PlayerException("player with '{$name}' already exists and controlledByAI do not match"); } return $player ?? (new Player())->setName($name)->setFlags($controlledByAI ? static::FLAG_AI_CONTROLLED : static::FLAG_NONE); }
public function makeSector($address) { /** * @var \Samsara\Eden\Entity\Sector $sectorDB */ $sectorDB = $this->sectorRepo->findOneBy(['address' => $address]); $zone = new Zone(); $this->sectors[$address] = new Sector($sectorDB, $zone); return $this->sectors[$address]; }
/** @inheritdoc */ public function getUserId(Credentials $credentials = null) { /** @var UsernamePasswordCredentials $credentials */ $user = $this->userRepository->findOneBy(['username' => $credentials->getUsername()]); /** @var User $user */ if (!$user || !$user->isPasswordValid($credentials->getPassword())) { return null; } return $user->getUserId(); }
/** * @param mixed $id * @return mixed|null|object */ public function reverseTransform($id) { if (!$id) { return null; } $entity = $this->repository->findOneBy(array($this->property => $id)); if (null === $entity) { throw new TransformationFailedException(sprintf('Can\'t find entity of class "%s" with property "%s" = "%s".', $this->class, $this->property, $id)); } return $entity; }
public function load(ObjectManager $manager) { $assignee = $this->userRepository->findOneBy(array('id' => 1)); $reporter = new User($assignee->getId(), User::TYPE_ORO); for ($i = 1; $i <= 10; $i++) { $branch = $this->branchRepository->findOneBy(array('name' => 'branchName' . $i)); $ticket = new Ticket(UniqueId::generate(), new TicketSequenceNumber(null), 'ticketSubject' . $i, 'ticketDescription' . $i, $branch, $reporter, $assignee, new Source(Source::PHONE), new Priority(Priority::PRIORITY_MEDIUM), new Status(Status::OPEN)); $manager->persist($ticket); } $manager->flush(); }
/** * {@inheritdoc} */ public function reverseTransform($value) { if (!$value) { return null; } $entity = $this->repository->findOneBy(array($this->identifier => $value)); if (null === $entity) { throw new TransformationFailedException(sprintf('Entity "%s" with identifier "%s"="%s" does not exist.', $this->repository->getClassName(), $this->identifier, $value)); } return $entity; }
/** * {@inheritDoc} */ public function authenticate() { $user = $this->repository->findOneBy(['email' => $this->identity]); if (!$user || !$user->isActive()) { return new Result(Result::FAILURE_IDENTITY_NOT_FOUND, null, ['User not found.']); } if (!$user->verifyPassword($this->credential)) { return new Result(Result::FAILURE_CREDENTIAL_INVALID, null, ['Invalid password.']); } return new Result(Result::SUCCESS, $user); }
/** * Finds routes that may potentially match the request. * * This may return a mixed list of class instances, but all routes returned * must extend the core symfony route. The classes may also implement * RouteObjectInterface to link to a content document. * * This method may not throw an exception based on implementation specific * restrictions on the url. That case is considered a not found - returning * an empty array. Exceptions are only used to abort the whole request in * case something is seriously broken, like the storage backend being down. * * Note that implementations may not implement an optimal matching * algorithm, simply a reasonable first pass. That allows for potentially * very large route sets to be filtered down to likely candidates, which * may then be filtered in memory more completely. * * @param Request $request A request against which to match. * * @return \Symfony\Component\Routing\RouteCollection with all Routes that * could potentially match $request. Empty collection if nothing can * match. */ public function getRouteCollectionForRequest(Request $request) { $slug = '/' . trim($request->getPathInfo(), '/'); $document = $this->repository->findOneBy(array('slug' => $slug)); $collection = new RouteCollection(); if ($document) { $controller = $this->templateControllers[$document->getTemplate()]; $route = new Route($document->getSlug(), array('_controller' => $controller, 'document' => $document)); $collection->add('test', $route); } return $collection; }
/** * @return ResourceViewModel * @throws NotFoundException * @throws ForbiddenException */ public function post() { $conversation = $this->getConversation(); if (!$this->isGranted(UserMessagePermissions::SEND_MESSAGE, $conversation)) { throw new ForbiddenException('User does not have permission to send a message in this conversation'); } $values = $this->validateIncomingData(MessageInputFilter::class); $sender = array_key_exists('sender', $values) && $values['sender'] ? $this->userRepository->findOneBy(['id' => $values['sender']]) : $this->identity(); $messageEntity = new MessageEntity($conversation, $sender, $values); $this->messageService->create($messageEntity); return new ResourceViewModel(['message' => $messageEntity], ['template' => 'messages/message']); }
public function load(ObjectManager $manager) { $author = $this->userRepository->findOneBy(array('id' => 1)); for ($i = 1; $i <= 10; $i++) { $ticket = $this->ticketRepository->findOneBy(array('subject' => 'ticketSubject' . $i)); for ($j = 1; $j <= 10; $j++) { $comment = new Comment('commentContent' . $i . '-' . $j, $ticket, new User($author->getId(), User::TYPE_ORO), false); $manager->persist($comment); } } $manager->flush(); }
/** * Performs an authentication * @param array * @return Nette\Security\Identity * @throws Nette\Security\AuthenticationException */ public function authenticate(array $credentials) { list($username, $password) = $credentials; $user = $this->users->findOneBy(array('username' => $username)); if (!$user) { throw new NS\AuthenticationException("User '{$username}' not found.", self::IDENTITY_NOT_FOUND); } if ($user->password !== $this->calculateHash($password)) { throw new NS\AuthenticationException("Invalid password.", self::INVALID_CREDENTIAL); } return new NS\Identity($user->id, $user->role, array('username' => $user->username, 'email' => $user->email)); }
public function testUpdate() { $this->entityManager->persist($this->user); $this->entityManager->flush(); $this->user->setUsername("Jorge Fernandez"); $this->user->setRoles(['ROLE_MANAGER', 'ROLE_ADMIN', 'ROLE_SUPER_ADMIN']); $this->entityManager->persist($this->user); $this->entityManager->flush(); $persistedUser = $this->userRepository->findOneBy(["email" => $this->user->getEmail()]); $this->assertEquals($this->user, $persistedUser); $this->assertEquals($this->user->getRoles(), $persistedUser->getRoles()); }
/** * @param array $credentials * @return null|User * @throws AuthenticationException */ public function authenticate(array $credentials) { list($email, $password) = $credentials; $user = $this->users->findOneBy(['email' => $email]); if (!$user) { throw new AuthenticationException('Invalid credentials.', self::IDENTITY_NOT_FOUND); } elseif (!Passwords::verify($password, $user->password)) { throw new AuthenticationException('Invalid credentials.', self::INVALID_CREDENTIAL); } elseif (Passwords::needsRehash($user->password)) { $user->setPassword($password); $this->em->flush(); } return $user; }
/** * Attempts to authenticate a GrantToken * * @param OAuthToken $token * * @return OAuthToken * * @throws AuthenticationException */ public function authenticate(TokenInterface $token) { $tokenValue = $token->getCredentials(); $accessToken = $this->accessTokenRepository->findOneBy(["token" => $tokenValue]); if ($accessToken === null) { throw new AuthenticationException("Invalid access token"); } if ($accessToken->isExpired()) { throw new AuthenticationException("Access token has expired"); } $user = $accessToken->getUser(); $token->setUser($user); return $token; }
/** * Remove a notification * * @param UserInterface $user * @param int $id */ public function remove(UserInterface $user, $id) { $notification = $this->repository->findOneBy(['id' => $id, 'user' => $user]); if ($notification) { $this->em->remove($notification); $this->em->flush($notification); } }
/** * Extract participant from provided data * * @param array $data * @return MessageUserInterface * @throws NotFoundException */ private function getParticipant(array $data) : MessageUserInterface { $user = $this->userRepository->findOneBy(['id' => $data['participant_id']]); if (!$user) { throw new NotFoundException('Participant does not exist'); } return $user; }
/** * {@inheritdoc} * * Instead of using EntityPersister of UnitOfWork, use O3Co CriteriaParser */ public function findOneBy(array $criteria, array $orderBy = array()) { if (!$this->getInterfaceCriteriaParser()) { return parent::findOneBy($criteria, $orderBy); } $query = $this->createInterfaceQuery($criteria, $orderBy, 1, 0); return $query->getNativeQuery()->getSingleResult(); }
/** * @param array $criteria * @param bool $exception * * @return object|null * * @throws NotFoundHttpException */ public function findOneBy(array $criteria, $exception = false) { $entity = $this->repository->findOneBy($criteria); if ($exception && !$entity) { throw new NotFoundHttpException('Unable to find entity.'); } return $entity; }
/** * @param string $directoryPath The path to the directory containing all of * the emote images and the pidgin "theme" file. */ public function populateDatabase($directoryPath) { $themeFile = $directoryPath . DIRECTORY_SEPARATOR . 'theme'; if (!is_file($themeFile)) { throw new \InvalidArgumentException(sprintf('Could not locate "%s".', $themeFile)); } if (false === ($themeHandle = fopen($themeFile, 'r'))) { throw new \InvalidArgumentException(sprintf('Could not open "%s".', $themeFile)); } // Seek through the theme until we find where the emotes are located. while (false !== ($line = fgets($themeHandle))) { $line = trim($line); if ('[default]' === $line) { break; } } if (feof($themeHandle)) { throw new \RuntimeException(sprintf('Could not find emote information in "%s".', $themeFile)); } while (false !== ($line = fgets($themeHandle))) { $line = trim($line); if (preg_match('/(?:! )?(\\S+)\\s+(.+)/', $line, $matches)) { $file = $matches[1]; $emoteCodes = preg_split('/\\s+/', $matches[2]); $sourcePath = $directoryPath . DIRECTORY_SEPARATOR . $file; $destinationPath = $this->dataStorage->getImageSourcePath($file); $emote = $this->emoteRepository->findOneBy(['path' => $file]); if (null === $emote) { $emote = new Emote(); $emote->setPath($file); if (null === $destinationPath) { $this->dataStorage->copyImageToSource($sourcePath); } $this->entityManager->persist($emote); $this->entityManager->flush($emote); } $newCodes = array_diff($emoteCodes, $emote->getTextCodesAsArray()); foreach ($newCodes as $code) { $textCode = new TextCode($emote, $code); $this->entityManager->persist($textCode); $this->entityManager->flush($textCode); } } } $this->entityManager->flush(); }