public function testGetActivityOwners()
 {
     $organization = new Organization();
     $organization->setName('Org');
     $user = new User();
     $user->setUsername('test');
     $emailUser = new EmailUser();
     $emailUser->setOrganization($organization);
     $emailUser->setOwner($user);
     $owners = [$emailUser];
     $emailMock = $this->getMockBuilder('Oro\\Bundle\\EmailBundle\\Entity\\EmailUser')->setMethods(['getFromEmailAddress', 'hasOwner', 'getOwner', 'getOrganization', 'getActivityTargetEntities'])->disableOriginalConstructor()->getMock();
     $emailMock->expects($this->once())->method('getFromEmailAddress')->willReturn($emailMock);
     $emailMock->expects($this->once())->method('getOwner')->willReturn($emailMock);
     $emailMock->expects($this->exactly(2))->method('getOrganization')->willReturn($organization);
     $emailMock->expects($this->exactly(1))->method('getActivityTargetEntities')->willReturn([]);
     $activityListMock = $this->getMockBuilder('Oro\\Bundle\\ActivityListBundle\\Entity\\ActivityList')->disableOriginalConstructor()->getMock();
     $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $repository = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $this->doctrineRegistryLink->expects($this->once())->method('getService')->willReturn($em);
     $em->expects($this->once())->method('getRepository')->willReturn($repository);
     $repository->expects($this->once())->method('findBy')->willReturn($owners);
     $activityOwnerArray = $this->emailActivityListProvider->getActivityOwners($emailMock, $activityListMock);
     $this->assertCount(1, $activityOwnerArray);
     $owner = $activityOwnerArray[0];
     $this->assertEquals($organization->getName(), $owner->getOrganization()->getName());
     $this->assertEquals($user->getUsername(), $owner->getUser()->getUsername());
 }
예제 #2
0
 /**
  * Test existing user modification
  */
 public function testOnFlushUpdateUser()
 {
     $args = new OnFlushEventArgs($this->em);
     $user = new User();
     $org = new Organization();
     $org->setId(1);
     $org->setName('test');
     $user->addOrganization($org);
     $newCalendar = new Calendar();
     $newCalendar->setOwner($user);
     $newCalendar->setOrganization($org);
     $newConnection = new CalendarConnection($newCalendar);
     $newCalendar->addConnection($newConnection);
     $calendarMetadata = new ClassMetadata(get_class($newCalendar));
     $connectionMetadata = new ClassMetadata(get_class($newConnection));
     $this->em->expects($this->any())->method('getClassMetadata')->will($this->returnValueMap([['Oro\\Bundle\\CalendarBundle\\Entity\\Calendar', $calendarMetadata], ['Oro\\Bundle\\CalendarBundle\\Entity\\CalendarConnection', $connectionMetadata]]));
     $calendarRepo = $this->getMockBuilder('\\Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $calendarRepo->expects($this->any())->method('findDefaultCalendar')->will($this->returnValue(false));
     $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($this->uow));
     $this->uow->expects($this->once())->method('getScheduledEntityInsertions')->will($this->returnValue([]));
     $this->uow->expects($this->once())->method('getScheduledEntityUpdates')->will($this->returnValue([$user]));
     $this->em->expects($this->any())->method('getRepository')->with('OroCalendarBundle:Calendar')->will($this->returnValue($calendarRepo));
     $this->em->expects($this->at(2))->method('persist')->with($this->equalTo($newCalendar));
     $this->em->expects($this->at(3))->method('persist')->with($this->equalTo($newConnection));
     $this->uow->expects($this->at(2))->method('computeChangeSet')->with($calendarMetadata, $newCalendar);
     $this->uow->expects($this->at(3))->method('computeChangeSet')->with($connectionMetadata, $newConnection);
     $this->listener->onFlush($args);
 }
 public function testPrecision()
 {
     $precision = '000 000.00';
     $this->assertNull($this->organization->getPrecision());
     $this->organization->setPrecision($precision);
     $this->assertEquals($precision, $this->organization->getPrecision());
 }
 public function load(ObjectManager $manager)
 {
     $defaultOrganization = new Organization();
     $defaultOrganization->setName('default')->setCurrency('USD')->setPrecision('000 000.00');
     $this->addReference('default_organization', $defaultOrganization);
     $manager->persist($defaultOrganization);
     $manager->flush();
 }
예제 #5
0
 public function testSetGetOrganizationContext()
 {
     $this->assertEmpty($this->token->getOrganizationContext());
     $organization = new Organization();
     $organization->setName('test');
     $this->token->setOrganizationContext($organization);
     $this->assertEquals($organization, $this->token->getOrganizationContext());
 }
예제 #6
0
 /**
  * @Route(
  *      "/switch-organization/{id}",
  *      name="oro_security_switch_organization", defaults={"id"=0}
  * )
  * @ParamConverter("organization", class="OroOrganizationBundle:Organization")
  * @throws NotFoundHttpException, AccessDeniedException
  */
 public function switchOrganizationAction(Organization $organization)
 {
     $token = $this->container->get('security.context')->getToken();
     if (!$token instanceof OrganizationContextTokenInterface || !$token->getUser() instanceof User || !$organization->isEnabled() || !$token->getUser()->getOrganizations()->contains($organization)) {
         throw new AccessDeniedException($this->get('translator')->trans('oro.security.organization.access_denied', array('%organization_name%' => $organization->getName())));
     }
     $token->setOrganizationContext($organization);
     return $this->redirect($this->generateUrl('oro_default'));
 }
 public function testSendNotNewEntity()
 {
     $organization = new Organization();
     $organization->setId(1);
     $user = new User();
     $user->setId(1);
     $this->emailUser->expects($this->exactly(1))->method('getOwner')->willReturn($user);
     $this->emailUser->expects($this->exactly(2))->method('getOrganization')->willReturn($organization);
     $this->topicPublisher->expects($this->once())->method('send')->with(WebSocketSendProcessor::getUserTopic($this->emailUser->getOwner(), $this->emailUser->getOrganization()), json_encode(['hasNewEmail' => false]));
     $this->processor->send([1 => ['entity' => $this->emailUser, 'new' => 0]]);
 }
예제 #8
0
 /**
  * @param User         $user
  * @param Organization $organization
  * @param array        $folderTypes
  * @param bool         $isSeen
  * @return array
  */
 public function getEmailUserList(User $user, Organization $organization, array $folderTypes = [], $isSeen = null)
 {
     $qb = $this->createQueryBuilder('eu');
     $qb->join('eu.folders', 'f')->join('f.origin', 'o')->andWhere($qb->expr()->eq('eu.owner', $user->getId()))->andWhere($qb->expr()->eq('eu.organization', $organization->getId()))->andWhere($qb->expr()->eq('o.isActive', ':active'))->setParameter('active', true);
     if ($folderTypes) {
         $qb->andWhere($qb->expr()->in('f.type', $folderTypes));
     }
     if ($isSeen !== null) {
         $qb->andWhere($qb->expr()->eq('eu.seen', ':seen'))->setParameter('seen', (bool) $isSeen);
     }
     return $qb->getQuery()->getResult();
 }
예제 #9
0
 /**
  * @param string       $key
  * @param Organization $entity
  */
 public function fillEntityData($key, $entity)
 {
     switch ($key) {
         case 'default':
             $organization = $this->securityFacade->getOrganization();
             if ($organization) {
                 $entity->setName($organization->getName());
             }
             return;
     }
     parent::fillEntityData($key, $entity);
 }
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     // load default organization
     $defaultOrganization = new Organization();
     $defaultOrganization->setName(self::MAIN_ORGANIZATION)->setEnabled(true);
     $this->addReference('default_organization', $defaultOrganization);
     $manager->persist($defaultOrganization);
     // load default business unit
     $defaultBusinessUnit = new BusinessUnit();
     $defaultBusinessUnit->setName(self::MAIN_BUSINESS_UNIT)->setOrganization($defaultOrganization);
     $this->addReference('default_business_unit', $defaultBusinessUnit);
     $manager->persist($defaultBusinessUnit);
     $manager->flush();
 }
 public function testGetVariableValues()
 {
     $organization = new Organization();
     $organization->setName('TestOrg');
     $user = new User();
     $user->setUsername('test');
     $user->setFirstName('FirstName');
     $user->setLastName('LastName');
     $this->securityFacade->expects($this->once())->method('getOrganization')->will($this->returnValue($organization));
     $this->securityFacade->expects($this->once())->method('getLoggedUser')->will($this->returnValue($user));
     $this->nameFormatter->expects($this->once())->method('format')->with($this->identicalTo($user))->will($this->returnValue('FullName'));
     $result = $this->provider->getVariableValues();
     $this->assertEquals(['userName' => 'test', 'userFirstName' => 'FirstName', 'userLastName' => 'LastName', 'userFullName' => 'FullName', 'organizationName' => 'TestOrg'], $result);
 }
 public function testGetOrganizations()
 {
     $user = new User();
     $disabledOrganization = new Organization();
     $organization = new Organization();
     $organization->setEnabled(true);
     $user->setOrganizations(new ArrayCollection(array($organization, $disabledOrganization)));
     $token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface');
     $this->securityContext->expects($this->once())->method('getToken')->will($this->returnValue($token));
     $token->expects($this->once())->method('getUser')->will($this->returnValue($user));
     $result = $this->twigExtension->getOrganizations();
     $this->assertInternalType('array', $result);
     $this->assertCount(1, $result);
     $this->assertSame($organization, $result[0]);
 }
예제 #13
0
 /**
  * Add user limitation
  *
  * @param DatagridConfiguration $config
  * @param string                $accessLevel
  * @param User                  $user
  * @param Organization          $organization
  *
  * @throws \Exception
  */
 protected function applyACL(DatagridConfiguration $config, $accessLevel, User $user, Organization $organization)
 {
     $where = $config->offsetGetByPath('[source][query][where][and]', []);
     /** todo: refactor this check usages */
     if ($accessLevel == AccessLevel::BASIC_LEVEL) {
         $where = array_merge($where, ['u.id = ' . $user->getId()]);
     } elseif ($accessLevel == AccessLevel::GLOBAL_LEVEL) {
         $leftJoins = $config->offsetGetByPath('[source][query][join][inner]', []);
         $leftJoins[] = ['join' => 'u.organizations', 'alias' => 'org'];
         $config->offsetSetByPath('[source][query][join][inner]', $leftJoins);
         $where = array_merge($where, ['org.id in (' . $organization->getId() . ')']);
     } elseif ($accessLevel !== AccessLevel::SYSTEM_LEVEL) {
         $resultBuIds = [];
         if ($accessLevel == AccessLevel::LOCAL_LEVEL) {
             $resultBuIds = $this->treeProvider->getTree()->getUserBusinessUnitIds($user->getId(), $organization->getId());
         } elseif ($accessLevel == AccessLevel::DEEP_LEVEL) {
             $resultBuIds = $this->treeProvider->getTree()->getUserSubordinateBusinessUnitIds($user->getId(), $organization->getId());
         }
         $leftJoins = $config->offsetGetByPath('[source][query][join][inner]', []);
         $leftJoins[] = ['join' => 'u.businessUnits', 'alias' => 'bu'];
         $config->offsetSetByPath('[source][query][join][inner]', $leftJoins);
         $where = array_merge($where, ['bu.id in (' . implode(', ', $resultBuIds) . ')']);
     }
     if (count($where)) {
         $config->offsetSetByPath('[source][query][where][and]', $where);
     }
 }
예제 #14
0
 public function testCreateCustomer()
 {
     $organization = new Organization();
     $organization->setName('test');
     $user = $this->getUser();
     $user->setOrganization($organization)->setFirstName('John')->setLastName('Doe');
     $this->assertEmpty($user->getCustomer());
     // createCustomer is triggered on prePersist event
     $user->createCustomer();
     $customer = $user->getCustomer();
     $this->assertInstanceOf('OroB2B\\Bundle\\CustomerBundle\\Entity\\Customer', $customer);
     $this->assertEquals($organization, $customer->getOrganization());
     $this->assertEquals('John Doe', $customer->getName());
     // new customer created only if it not defined
     $user->setFirstName('Jane');
     $user->createCustomer();
     $this->assertEquals('John Doe', $user->getCustomer()->getName());
 }
예제 #15
0
 /**
  * @Route(
  *      "/switch-organization/{id}",
  *      name="oro_security_switch_organization", defaults={"id"=0}
  * )
  *
  * @param Organization $organization
  *
  * @return RedirectResponse , AccessDeniedException
  */
 public function switchOrganizationAction(Organization $organization)
 {
     $token = $this->container->get('security.context')->getToken();
     $user = $token->getUser();
     if (!$token instanceof OrganizationContextTokenInterface || !$token->getUser() instanceof User || !$organization->isEnabled() || !$token->getUser()->getOrganizations()->contains($organization)) {
         throw new AccessDeniedException($this->get('translator')->trans('oro.security.organization.access_denied', ['%organization_name%' => $organization->getName()]));
     }
     $event = new OrganizationSwitchBefore($user, $token->getOrganizationContext(), $organization);
     $this->get('event_dispatcher')->dispatch(OrganizationSwitchBefore::NAME, $event);
     $organization = $event->getOrganizationToSwitch();
     if (!$user->getOrganizations(true)->contains($organization)) {
         $message = $this->get('translator')->trans('oro.security.organization.access_denied', ['%organization_name%' => $organization->getName()]);
         throw new AccessDeniedException($message);
     }
     $token->setOrganizationContext($organization);
     $event = new OrganizationSwitchAfter($user, $organization);
     $this->get('event_dispatcher')->dispatch(OrganizationSwitchAfter::NAME, $event);
     return $this->redirect($this->generateUrl('oro_default'));
 }
예제 #16
0
 public function testTokenShouldBeAuthenticated()
 {
     $token = new OAuthToken('token');
     $token->setResourceOwnerName('google');
     $organization = new Organization();
     $organization->setEnabled(true);
     $token->setOrganizationContext($organization);
     $userResponse = $this->getMock('HWI\\Bundle\\OAuthBundle\\OAuth\\Response\\UserResponseInterface');
     $resourceOwner = $this->getMock('HWI\\Bundle\\OAuthBundle\\OAuth\\ResourceOwnerInterface');
     $resourceOwner->expects($this->any())->method('getName')->will($this->returnValue('google'));
     $resourceOwner->expects($this->any())->method('getUserInformation')->will($this->returnValue($userResponse));
     $this->resourceOwnerMap->expects($this->any())->method('getResourceOwnerByName')->will($this->returnValue($resourceOwner));
     $user = new User();
     $user->addOrganization($organization);
     $this->userProvider->expects($this->any())->method('loadUserByOAuthUserResponse')->with($userResponse)->will($this->returnValue($user));
     $resultToken = $this->oauthProvider->authenticate($token);
     $this->assertInstanceOf('Oro\\Bundle\\SSOBundle\\Security\\OAuthToken', $resultToken);
     $this->assertSame($user, $resultToken->getUser());
     $this->assertEquals('google', $resultToken->getResourceOwnerName());
     $this->assertTrue($resultToken->isAuthenticated());
 }
 /**
  * {@inheritdoc}
  * @dataProvider supportedMethods
  */
 public function testProcessSupportedRequest($method, $isValid, $isProcessed)
 {
     $organization = null;
     if ($isValid) {
         $organization = new Organization();
         $organization->setName('test');
         $organizationToken = $this->getMock('Oro\\Bundle\\SecurityBundle\\Authentication\\Token\\OrganizationContextTokenInterface');
         $organizationToken->expects($this->any())->method('getOrganizationContext')->willReturn($organization);
         $this->securityFacade->expects($this->any())->method('getToken')->willReturn($organizationToken);
         $this->form->expects($this->at(2))->method('get')->with('passwordGenerate')->will($this->returnValue($this->passwordGenerateForm));
         $this->form->expects($this->at(3))->method('get')->with('sendEmail')->will($this->returnValue($this->sendEmailForm));
         $this->passwordGenerateForm->expects($this->once())->method('getData')->will($this->returnValue(false));
         $this->sendEmailForm->expects($this->once())->method('getData')->will($this->returnValue(false));
     }
     $this->form->expects($this->any())->method('isValid')->will($this->returnValue($isValid));
     $this->request->setMethod($method);
     $this->form->expects($this->once())->method('submit')->with($this->request);
     $this->assertEquals($isProcessed, $this->handler->process($this->entity));
     if ($organization) {
         $this->assertEquals($organization, $this->entity->getOrganization());
         $this->assertTrue($this->entity->hasOrganization($organization));
     }
 }
예제 #18
0
 public function testCreateAccount()
 {
     $organization = new Organization();
     $organization->setName('test');
     $user = $this->getUser();
     $user->setOrganization($organization)->setFirstName('John')->setLastName('Doe')->setOwner(new User());
     $this->assertEmpty($user->getAccount());
     $address = new AccountAddress();
     $user->addAddress($address);
     $this->assertContains($address, $user->getAddresses());
     $backendUser = new User();
     $user->setOwner($backendUser);
     $this->assertEquals($user->getOwner(), $backendUser);
     // createAccount is triggered on prePersist event
     $user->createAccount();
     $account = $user->getAccount();
     $this->assertInstanceOf('OroB2B\\Bundle\\AccountBundle\\Entity\\Account', $account);
     $this->assertEquals($organization, $account->getOrganization());
     $this->assertEquals('John Doe', $account->getName());
     // new account created only if it not defined
     $user->setFirstName('Jane');
     $user->createAccount();
     $this->assertEquals('John Doe', $user->getAccount()->getName());
 }
예제 #19
0
 public function testAddRemoveUser()
 {
     $org = new Organization();
     $user = new User();
     $user->setId(uniqid());
     $this->assertFalse($org->hasUser($user));
     $org->addUser($user);
     $users = $org->getUsers()->toArray();
     $this->assertCount(1, $users);
     $this->assertTrue($org->hasUser($user));
     $this->assertEquals($user, reset($users));
     $org->removeUser($user);
     $this->assertFalse($org->hasUser($user));
 }
 /**
  * @param string $accountName
  * @param string $userFirstName
  * @param string $userLastName
  * @param bool $isOrder
  * @return Order|Quote
  */
 protected function createMainEntity($accountName, $userFirstName, $userLastName, $isOrder = false)
 {
     $accountUser = $this->createAccountUser($accountName);
     $owner = new User();
     $owner->setFirstName($userFirstName . ' owner')->setLastName($userLastName . ' owner')->setSalt(null);
     $organization = new Organization();
     $organization->setName($userFirstName . ' ' . $userLastName . ' org');
     $entity = $isOrder ? new Order() : new Quote();
     $entity->setAccount($accountUser->getAccount())->setAccountUser($accountUser)->setOwner($owner)->setOrganization($organization);
     return $entity;
 }
예제 #21
0
 public function testOrganizations()
 {
     $user = new User();
     $disabledOrganization = new Organization();
     $organization = new Organization();
     $organization->setEnabled(true);
     $user->setOrganizations(new ArrayCollection(array($organization)));
     $this->assertContains($organization, $user->getOrganizations());
     $user->removeOrganization($organization);
     $this->assertNotContains($organization, $user->getOrganizations());
     $user->addOrganization($organization);
     $this->assertContains($organization, $user->getOrganizations());
     $user->addOrganization($disabledOrganization);
     $result = $user->getOrganizations(true);
     $this->assertTrue($result->count() == 1);
     $this->assertSame($result->first(), $organization);
 }
예제 #22
0
 public function testGetApiKey()
 {
     $entity = $this->getUser();
     $this->assertEmpty($entity->getApiKeys(), 'Should return some key, even if is not present');
     $organization1 = new Organization();
     $organization1->setName('test1');
     $organization2 = new Organization();
     $organization2->setName('test2');
     $apiKey1 = new UserApi();
     $apiKey1->setApiKey($apiKey1->generateKey());
     $apiKey1->setOrganization($organization1);
     $apiKey2 = new UserApi();
     $apiKey2->setApiKey($apiKey2->generateKey());
     $apiKey2->setOrganization($organization2);
     $entity->addApiKey($apiKey1);
     $entity->addApiKey($apiKey2);
     $this->assertSame($apiKey1->getApiKey(), $entity->getApiKeys()[0]->getApiKey(), 'Should delegate call to userApi entity');
     $this->assertEquals(new ArrayCollection([$apiKey1, $apiKey2]), $entity->getApiKeys());
     $entity->removeApiKey($apiKey2);
     $this->assertEquals(new ArrayCollection([$apiKey1]), $entity->getApiKeys());
 }
예제 #23
0
 /**
  * Add ACL Check condition to the Query Builder
  *
  * @param QueryBuilder $queryBuilder
  * @param string       $accessLevel
  * @param User         $user
  * @param Organization $organization
  */
 protected function addAcl(QueryBuilder $queryBuilder, $accessLevel, User $user, Organization $organization)
 {
     if ($accessLevel == AccessLevel::BASIC_LEVEL) {
         $queryBuilder->andWhere($queryBuilder->expr()->in('users.id', [$user->getId()]));
     } elseif ($accessLevel == AccessLevel::GLOBAL_LEVEL) {
         $queryBuilder->join('users.organizations', 'org')->andWhere($queryBuilder->expr()->in('org.id', [$organization->getId()]));
     } elseif ($accessLevel !== AccessLevel::SYSTEM_LEVEL) {
         if ($accessLevel == AccessLevel::LOCAL_LEVEL) {
             $resultBuIds = $this->treeProvider->getTree()->getUserBusinessUnitIds($user->getId(), $organization->getId());
         } elseif ($accessLevel == AccessLevel::DEEP_LEVEL) {
             $resultBuIds = $this->treeProvider->getTree()->getUserSubordinateBusinessUnitIds($user->getId(), $organization->getId());
         }
         $queryBuilder->join('users.businessUnits', 'bu')->andWhere($queryBuilder->expr()->in('bu.id', $resultBuIds));
     }
 }
예제 #24
0
 public function testId()
 {
     $this->assertNull($this->organization->getId());
 }
 /**
  * Get user topic
  *
  * @param User $user
  * @param Organization $organization
  * @return string
  */
 public static function getUserTopic(User $user, Organization $organization)
 {
     return sprintf(self::TOPIC, $user->getId(), $organization->getId());
 }
예제 #26
0
 protected function getTestOrganization()
 {
     $organization = new Organization();
     $organization->setId(1);
     return $organization;
 }
예제 #27
0
 /**
  * Get user topic
  *
  * @param User|int $user
  * @param Organization $organization
  * @return string
  */
 public static function getUserTopic($user, Organization $organization)
 {
     $userId = $user instanceof User ? $user->getId() : $user;
     return sprintf(self::TOPIC, $userId, $organization->getId());
 }
 /**
  * Check
  * @param User         $user
  * @param Organization $organization
  * @param string       $class
  * @param string       $username
  * @param int          $organizationId
  * @param int          $expires
  * @param string       $hash
  */
 protected function checkUserData(User $user, Organization $organization, $class, $username, $organizationId, $expires, $hash)
 {
     if (!$user instanceof UserInterface) {
         throw new \RuntimeException(sprintf('The UserProviderInterface implementation must return an instance of UserInterface,
                  but returned "%s".', get_class($user)));
     }
     if (!$organization instanceof Organization) {
         throw new \RuntimeException(sprintf('Can not find organization with id "%s".', $organizationId));
     }
     if (!$organization->isEnabled()) {
         throw new \RuntimeException(sprintf('Organization "%s" is not active.', $organization->getName()));
     }
     if (!$user->getOrganizations()->contains($organization)) {
         throw new AuthenticationException(sprintf('User "%s" does not have access to organization "%s".', $username, $organization->getName()));
     }
     $isHashesIdentical = $this->compareHashes($hash, $this->generateCookieHash($class, $username, $expires, $user->getPassword()));
     if (true !== $isHashesIdentical) {
         throw new AuthenticationException('The cookie\'s hash is invalid.');
     }
     if ($expires < time()) {
         throw new AuthenticationException('The cookie has expired.');
     }
 }
예제 #29
0
 /**
  * @param Organization $organization
  *
  * @return null|BusinessUnit
  */
 protected function getCurrentBusinessUnit(Organization $organization)
 {
     $user = $this->getCurrentUser();
     if (!$user) {
         return null;
     }
     $businessUnits = $user->getBusinessUnits()->filter(function (BusinessUnit $businessUnit) use($organization) {
         return $businessUnit->getOrganization()->getId() === $organization->getId();
     });
     if (!$this->isAssignGranted) {
         return $businessUnits->first();
     }
     // if assign is granted then only allowed business units can be used
     $allowedBusinessUnits = $this->businessUnitManager->getBusinessUnitIds();
     /** @var BusinessUnit $businessUnit */
     foreach ($businessUnits as $businessUnit) {
         if (in_array($businessUnit->getId(), $allowedBusinessUnits)) {
             return $businessUnit;
         }
     }
     return null;
 }
 /**
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage User test_user is not in organization test_organization
  */
 public function testUserNotInOrganization()
 {
     $username = '******';
     $user = new User();
     $user->setUsername($username);
     $organizationName = 'test_organization';
     $organization = new Organization();
     $organization->setName($organizationName);
     $organization->setEnabled(true);
     $event = $this->getEvent();
     /** @var \PHPUnit_Framework_MockObject_MockObject  $input */
     $input = $event->getInput();
     $input->expects($this->at(0))->method('getParameterOption')->with('--' . ConsoleContextListener::OPTION_USER)->will($this->returnValue($username));
     $input->expects($this->at(1))->method('getParameterOption')->with('--' . ConsoleContextListener::OPTION_ORGANIZATION)->will($this->returnValue($organizationName));
     $this->userManager->expects($this->once())->method('findUserByUsernameOrEmail')->with($username)->will($this->returnValue($user));
     $this->organizationRepository->expects($this->once())->method('findOneBy')->with(['name' => $organizationName])->will($this->returnValue($organization));
     $this->listener->onConsoleCommand($event);
 }