246 code examples of PHP Oro\Component\Testing\ReflectionUtil extracted from open source projects
private function getActions(TreeExecutor $action): array
{
return ReflectionUtil::getPropertyValue($action, 'actions');
}
public function addPostAction(TreeExecutor $treeExecutor, ActionInterface $action, bool $breakOnFailure)
{
$actionData = [];
if ($action instanceof TreeExecutor) {
$actionData = [
'_type' => TreeExecutor::ALIAS,
'actions' => $this->getActions($action),
];
} elseif ($action instanceof ArrayAction) {
$actionData = $action->toArray();
}
$conditionData = $this->getCondition($action);
if ($conditionData) {
$actionData['condition'] = $conditionData;
}
$treeActions = $this->getActions($treeExecutor);
$treeActions[] = [
'instance' => $actionData,
'breakOnFailure' => $breakOnFailure,
];
ReflectionUtil::setPropertyValue($treeExecutor, 'actions', $treeActions);
}
private function getEntitiesScheduledForWorkflowStart(WorkflowStartListener $listener): mixed
{
return ReflectionUtil::getPropertyValue($listener, 'entitiesScheduledForWorkflowStart');
}
private function getDeepLevel(WorkflowStartListener $listener): mixed
{
return ReflectionUtil::getPropertyValue($listener, 'deepLevel');
}
private function getEntitySerializedData(WorkflowItem $entity): mixed
{
return ReflectionUtil::getPropertyValue($entity, 'serializedData');
}
private function getEntitySerializer(WorkflowItem $entity): mixed
{
return ReflectionUtil::getPropertyValue($entity, 'serializer');
}
private function getExtensionScheduled(AbstractEventTriggerExtension $extension): mixed
{
return ReflectionUtil::getPropertyValue($extension, 'scheduled');
}
private function getExtensionRemovedEntityHashes(AbstractEventTriggerExtension $extension): mixed
{
return ReflectionUtil::getPropertyValue($extension, 'removedEntityHashes');
}
private function getExtensionScheduledProcesses(AbstractEventTriggerExtension $extension): mixed
{
return ReflectionUtil::getPropertyValue($extension, 'scheduledProcesses');
}
private function getExtensionTriggers(AbstractEventTriggerExtension $extension): mixed
{
return ReflectionUtil::getPropertyValue($extension, 'triggers');
}
public function testGetId()
{
$this->assertNull($this->transitionRecord->getId());
$value = 42;
ReflectionUtil::setId($this->transitionRecord, $value);
$this->assertSame($value, $this->transitionRecord->getId());
}
public function testGetId()
{
$this->assertNull($this->step->getId());
$value = 42;
ReflectionUtil::setId($this->step, $value);
$this->assertSame($value, $this->step->getId());
}
public function testGetId()
{
$this->assertNull($this->identity->getId());
$value = 1;
ReflectionUtil::setId($this->identity, $value);
$this->assertSame($value, $this->identity->getId());
}
/**
* @depends testGetResult
*/
public function testGetResultUnserialized()
{
ReflectionUtil::setPropertyValue($this->workflowItem, 'result', null);
$this->assertInstanceOf(WorkflowResult::class, $this->workflowItem->getResult());
$this->assertTrue($this->workflowItem->getResult()->isEmpty());
}
public function testGetAttributeStepKeyNoStepException()
{
$this->expectException(WorkflowException::class);
$this->expectExceptionMessage("Workflow entity ACL with ID 1 doesn't have workflow step");
ReflectionUtil::setId($this->entityAcl, 1);
$this->entityAcl->getAttributeStepKey();
}
public function testGetId()
{
$this->assertNull($this->entityAcl->getId());
$value = 42;
ReflectionUtil::setId($this->entityAcl, $value);
$this->assertSame($value, $this->entityAcl->getId());
}
public function testGetAclAttributeStepKeyNoAclException()
{
$this->expectException(WorkflowException::class);
$this->expectExceptionMessage("Workflow ACL identity with ID 1 doesn't have entity ACL");
ReflectionUtil::setId($this->aclIdentity, 1);
$this->aclIdentity->getAclAttributeStepKey();
}
public function testGetId()
{
$this->assertNull($this->aclIdentity->getId());
$value = 42;
ReflectionUtil::setId($this->aclIdentity, $value);
$this->assertSame($value, $this->aclIdentity->getId());
}
public function testGetId()
{
$this->assertNull($this->entity->getId());
$testValue = 1;
ReflectionUtil::setId($this->entity, $testValue);
$this->assertSame($testValue, $this->entity->getId());
}
public function testGetId()
{
self::assertNull($this->entity->getId());
$testValue = 1;
ReflectionUtil::setId($this->entity, $testValue);
self::assertSame($testValue, $this->entity->getId());
}
private function getForPersistPropertyValue(): mixed
{
return ReflectionUtil::getPropertyValue($this->processTriggersConfigurator, 'forPersist');
}
private function getForRemovePropertyValue(): mixed
{
return ReflectionUtil::getPropertyValue($this->processTriggersConfigurator, 'forRemove');
}
private function getDirtyPropertyValue(): mixed
{
return ReflectionUtil::getPropertyValue($this->processTriggersConfigurator, 'dirty');
}
private function getToPersistPropertyValue(): mixed
{
return ReflectionUtil::getPropertyValue($this->processDefinitionsConfigurator, 'toPersist');
}
private function getToRemovePropertyValue(): mixed
{
return ReflectionUtil::getPropertyValue($this->processDefinitionsConfigurator, 'toRemove');
}
private function getDirtyPropertyValue(): mixed
{
return ReflectionUtil::getPropertyValue($this->processDefinitionsConfigurator, 'dirty');
}
private function createProcessTrigger(int $id): ProcessTrigger
{
$definition = (new ProcessDefinition())
->setName('name')
->setLabel('label')
->setRelatedEntity(\stdClass::class);
$processTrigger = new ProcessTrigger();
ReflectionUtil::setId($processTrigger, $id);
$processTrigger->setDefinition($definition);
return $processTrigger;
}
protected function setUp(): void
{
$this->initClient();
$provider = $this->getContainer()->get('oro_workflow.configuration.provider.process_config');
ReflectionUtil::setPropertyValue($provider, 'configDirectory', '/Tests/Functional/Command/DataFixtures/');
}
public function testValidateUserEmailIsNotUnique()
{
$newUserEmail = 'foo';
$newUser = new User();
ReflectionUtil::setId($newUser, 1);
$newUser->setEmail($newUserEmail);
$existingUser = new User();
ReflectionUtil::setId($existingUser, 2);
$existingUser->setEmail($newUserEmail);
$this->userManager->expects(self::once())
->method('findUserByEmail')
->with($newUserEmail)
->willReturn($existingUser);
$constraint = new UniqueUserEmail();
$this->validator->validate($newUser, $constraint);
$this->buildViolation($constraint->message)
->atPath('property.path.email')
->setInvalidValue($newUserEmail)
->assertRaised();
}
public function testValidateUserEmailIsUnique()
{
$newUserEmail = 'foo';
$newUser = new User();
ReflectionUtil::setId($newUser, 1);
$newUser->setEmail($newUserEmail);
$this->userManager->expects(self::once())
->method('findUserByEmail')
->with($newUserEmail)
->willReturn($newUser);
$this->validator->validate($newUser, new UniqueUserEmail());
$this->assertNoViolation();
}
private function getUserWithData(): User
{
$user = new User();
ReflectionUtil::setId($user, 123);
$user->setEnabled(true);
$user->setUsername('john');
$user->setEmail('[email protected]');
$user->setFirstName('John');
$user->setLastName('Doe');
$user->setLastLogin(new \DateTime('01-01-2010'));
$user->setCreatedAt(new \DateTime('01-01-2000'));
return $user;
}
/**
* Test bad scenario for isCurrentUser
*/
public function testIsCurrentUserFalse()
{
$userMock = $this->createMock(User::class);
$userMock->expects($this->once())
->method('getId')
->willReturn(1);
$this->token->expects($this->any())
->method('getUser')
->willReturn(null);
$this->tokenAccessor->expects($this->once())
->method('getToken')
->willReturn($this->token);
ReflectionUtil::callMethod($this->subscriber, 'isCurrentUser', [$userMock]);
}
public function testId()
{
$entity = new UserApi();
self::assertNull($entity->getId());
$id = 1;
ReflectionUtil::setId($entity, $id);
self::assertSame($id, $entity->getId());
}
public function testClone()
{
$role = new Role();
ReflectionUtil::setId($role, 1);
$copy = clone $role;
$this->assertEmpty($copy->getId());
}
protected function setUp(): void
{
$this->em = $this->createMock(EntityManagerInterface::class);
$this->translationRepository = $this->createMock(TranslationRepository::class);
$this->translationKeyRepository = $this->createMock(TranslationKeyRepository::class);
$this->translationManager = $this->createMock(TranslationManager::class);
$this->fileBasedLanguageHelper = $this->createMock(FileBasedLanguageHelper::class);
$this->language = new Language();
ReflectionUtil::setId($this->language, 1);
$this->language->setCode(self::TEST_LOCALE);
$this->language->setLocalFilesLanguage(false);
$languageRepository = $this->createMock(LanguageRepository::class);
$languageRepository->expects(self::any())
->method('findOneBy')
->willReturn($this->language);
$connection = $this->createMock(Connection::class);
$this->em->expects(self::any())
->method('getConnection')
->willReturn($connection);
$this->em->expects(self::any())
->method('getRepository')
->with(Translation::class)
->willReturn($this->translationRepository);
$doctrine = $this->createMock(ManagerRegistry::class);
$doctrine->expects(self::any())
->method('getManagerForClass')
->with(Translation::class)
->willReturn($this->em);
$doctrine->expects(self::any())
->method('getRepository')
->willReturnMap([
[TranslationKey::class, null, $this->translationKeyRepository],
[Language::class, null, $languageRepository],
]);
$this->persister = new DatabasePersister(
$doctrine,
$this->translationManager,
$this->fileBasedLanguageHelper
);
}
private function createTranslation(
string $key,
?string $value,
string $locale,
string $domain,
int $id = null
): Translation {
$translationKey = new TranslationKey();
$translationKey->setKey($key)->setDomain($domain);
$language = new Language();
$language->setCode($locale);
$translation = new Translation();
ReflectionUtil::setId($translation, $id);
$translation->setTranslationKey($translationKey);
$translation->setValue($value);
$translation->setLanguage($language);
return $translation;
}
private static function getData(UpdateTranslatableDictionariesListener $listener): array
{
return ReflectionUtil::getPropertyValue($listener, 'data');
}
public function testPersistWithSystemScopeDataAndLanguageShouldBeFilesBased(): void
{
//change the fileBasedLanguagesPath parameter to emulate the case when there is dumped translations
//in translations directory.
$translationsPath = realpath(__DIR__ . '/../Stub/translations');
$helper = self::getContainer()->get('oro_translation.helper.file_based_language');
ReflectionUtil::setPropertyValue($helper, 'fileBasedLanguagesPath', $translationsPath);
$language = $this->getReference(LoadLanguages::LANGUAGE2);
$translationKey = $this->getReference('tk-translation.trans5-test_domain');
$catalogData = [
'test_domain' => [
'translation.trans5' => 'translation.trans5',
],
];
$keyCount = $this->getEntityCount(TranslationKey::class);
$translationCount = $this->getEntityCount(Translation::class);
$this->getPersister()->persist(LoadLanguages::LANGUAGE2, $catalogData, Translation::SCOPE_SYSTEM);
$this->assertEquals($keyCount, $this->getEntityCount(TranslationKey::class));
$this->assertEquals($translationCount, $this->getEntityCount(Translation::class));
$updatedEntity = $this->getTranslationEntity($language, $translationKey);
self::assertEquals(Translation::SCOPE_SYSTEM, $updatedEntity->getScope());
self::assertTrue($language->isLocalFilesLanguage());
}
protected function setUp(): void
{
$this->initClient();
// change the translationServiceAdapter at the command instance to the stub
// to be able to work with local archive instead of real calls to the remote service.
$archivePath = realpath(__DIR__ . '/../../Stub/translations.zip');
$translationServiceAdapter = new TranslationServiceAdapterStub($archivePath);
$this->loader = self::getContainer()->get('oro_translation.catalogue_loader.crowdin');
ReflectionUtil::setPropertyValue($this->loader, 'translationServiceAdapter', $translationServiceAdapter);
}
protected function setUp(): void
{
$this->initClient();
$this->loadFixtures([LoadTranslations::class]);
$this->tempDir = $this->getTempDir('dump_translation_command');
$this->translationReader = self::getContainer()->get('translation.reader');
// change the translationServiceAdapter at the command instance to the stub
// to be able to work with local archive instead of real calls to the remote service.
$archivePath = realpath(__DIR__ . '/../Stub/translations.zip');
$translationServiceAdapter = new TranslationServiceAdapterStub($archivePath);
$loader = self::getContainer()->get('oro_translation.catalogue_loader.crowdin');
ReflectionUtil::setPropertyValue($loader, 'translationServiceAdapter', $translationServiceAdapter);
// change the directory of the dumped files to the temp directory
// because default translation path from the translator.default_path parameter can be
// forbidden to write at the test instances.
$command = self::getContainer()->get(DumpTranslationToFilesCommand::class);
ReflectionUtil::setPropertyValue($command, 'targetPath', $this->tempDir);
}
/**
* @param int|null $identifier
*/
public function getSegment(array $definition = null, string $entity = null, bool $identifier = null): Segment
{
$segment = new Segment();
ReflectionUtil::setId($segment, $identifier ?? self::TEST_IDENTIFIER);
$segment->setEntity($entity ?? self::TEST_ENTITY);
$segment->setDefinition(QueryDefinitionUtil::encodeDefinition($definition ?? $this->getDefaultDefinition()));
return $segment;
}
public function testGetId()
{
$this->assertNull($this->object->getId());
$testValue = 42;
ReflectionUtil::setId($this->object, $testValue);
$this->assertEquals($testValue, $this->object->getId());
}
/**
* @param BatchItem[] $items
*/
private function setItems(array $items)
{
$val = [];
foreach ($items as $item) {
$key = ReflectionUtil::callMethod($this->manager, 'getKey', [$item->getOid()]);
$val[$key] = $item;
}
ReflectionUtil::setPropertyValue($this->manager, 'items', $val);
}
private function setItem(ObjectIdentity $oid, $state, MutableAclInterface $acl = null)
{
$key = ReflectionUtil::callMethod($this->manager, 'getKey', [$oid]);
ReflectionUtil::setPropertyValue(
$this->manager,
'items',
[$key => new BatchItem($oid, $state, $acl)]
);
}
private function getPermission(
string $id,
string $name,
bool $applyToAll,
array $applyEntities,
array $excludeEntities,
array $groups
): Permission {
$permission = new Permission();
ReflectionUtil::setId($permission, $id);
$permission
->setName($name)
->setApplyToAll($applyToAll)
->setGroupNames($groups);
foreach ($applyEntities as $entity) {
$permission->addApplyToEntity($this->getPermissionEntity($entity));
}
foreach ($excludeEntities as $entity) {
$permission->addExcludeEntity($this->getPermissionEntity($entity));
}
return $permission;
}
public function testRefreshNotExistingUser()
{
// any route just to initialize security context
$this->client->request('GET', $this->getUrl('oro_user_index'));
$user = new User();
ReflectionUtil::setId($user, 999);
$this->getContainer()->get('security.token_storage')->getToken()->setUser($user);
/** @var EntityManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine')->getManager();
$this->assertInstanceOf('Doctrine\ORM\EntityManager', $entityManager);
$entityManager->clear();
$this->assertNull($this->getContainer()->get('security.token_storage')->getToken());
}
private function appendPermissionConfig(PermissionConfigurationProvider $provider, array $newPermissions)
{
$provider->ensureCacheWarmedUp();
ReflectionUtil::setPropertyValue(
$provider,
'config',
array_merge(ReflectionUtil::getPropertyValue($provider, 'config'), $newPermissions)
);
}
public function testSecurityShouldBeMergedCorrectly()
{
$originalConfig = [
[
'access_decision_manager' => [
'strategy' => 'unanimous',
],
'firewalls' => [
'dev' => [
'pattern' => '^/(_(profiler|wdt)|css|images|js)/',
'security' => false,
],
'main' => [
'pattern' => '^/',
'provider' => 'chain_provider',
'organization-form-login' => [
'csrf_token_generator' => 'security.csrf.token_manager',
'check_path' => 'oro_user_security_check',
'login_path' => 'oro_user_security_login',
],
'logout' => [
'path' => 'oro_user_security_logout',
],
'organization-remember-me' => [
'key' => '%secret%',
'name' => 'CRMRM',
'lifetime' => 1209600,
'httponly' => true,
],
'anonymous' => false,
],
],
],
[
'firewalls' => [
'main' => [
'organization-http-basic' => [
'realm' => 'Secured REST Area',
],
'provider' => 'oro_user',
'http-basic' => false,
'organization-form-login' => false,
'logout' => false,
'organization-remember-me' => false,
'anonymous' => true,
],
],
'acl' => [
'connection' => 'default',
],
],
];
$additionalConfig = [
'firewalls' => [
'oauth' => [
'resource_owners' => [
'google' => '/login/check-google',
],
],
],
];
$expectedConfig = $originalConfig;
$expectedConfig[0]['firewalls']['oauth'] = $additionalConfig['firewalls']['oauth'];
$containerBuilder = new ExtendedContainerBuilder();
$containerBuilder->setExtensionConfig('security', $originalConfig);
$platformExtension = new OroPlatformExtension();
ReflectionUtil::callMethod(
$platformExtension,
'mergeConfigIntoOne',
[$containerBuilder, 'security', $additionalConfig]
);
$this->assertEquals($expectedConfig, $containerBuilder->getExtensionConfig('security'));
}
public function testGetId(): void
{
$id = UUIDGenerator::v4();
$entity = new NotificationAlert();
ReflectionUtil::setId($entity, $id);
self::assertSame($id, $entity->getId());
}
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testGetEntityViewModels(): void
{
$createdByAvatar = new File();
$createdBy = $this->createMock(TestUser::class);
$createdBy->expects(self::once())
->method('getId')
->willReturn(100);
$createdBy->expects(self::once())
->method('getAvatar')
->willReturn($createdByAvatar);
$updatedBy = $this->createMock(TestUser::class);
$updatedBy->expects(self::once())
->method('getId')
->willReturn(100);
$updatedBy->expects(self::once())
->method('getAvatar')
->willReturn(null);
$note = new Note();
ReflectionUtil::setId($note, 123);
$note
->setMessage('test message')
->setCreatedAt(new \DateTime('2014-01-20 10:30:40', new \DateTimeZone('UTC')))
->setUpdatedAt(new \DateTime('2014-01-21 10:30:40', new \DateTimeZone('UTC')))
->setOwner($createdBy)
->setUpdatedBy($updatedBy);
$this->authorizationChecker->expects(self::exactly(4))
->method('isGranted')
->willReturnMap([
['EDIT', $note, true],
['DELETE', $note, false],
['VIEW', $createdBy, true],
['VIEW', $updatedBy, false],
]);
$this->entityNameResolver->expects(self::exactly(2))
->method('getName')
->willReturnMap([
[$createdBy, null, null, 'User1'],
[$updatedBy, null, null, 'User2'],
]);
$this->pictureSourcesProvider->expects(self::exactly(2))
->method('getFilteredPictureSources')
->willReturnMap([
[
$createdByAvatar,
'avatar_xsmall',
[
'src' => 'image1_xsmall.jpg',
'sources' => [
[
'srcset' => 'image1_xsmall.jpg.webp',
'type' => 'image/webp',
],
],
],
],
[
null,
'avatar_xsmall',
[
'src' => null,
'sources' => [],
],
],
]);
self::assertEquals(
[
[
'id' => 123,
'message' => 'test message',
'createdAt' => '2014-01-20T10:30:40+00:00',
'updatedAt' => '2014-01-21T10:30:40+00:00',
'hasUpdate' => true,
'editable' => true,
'removable' => false,
'createdBy' => 'User1',
'createdBy_id' => 100,
'createdBy_viewable' => true,
'createdBy_avatarPicture' => [
'src' => 'image1_xsmall.jpg',
'sources' => [
[
'srcset' => 'image1_xsmall.jpg.webp',
'type' => 'image/webp',
],
],
],
'updatedBy' => 'User2',
'updatedBy_id' => 100,
'updatedBy_viewable' => false,
'updatedBy_avatarPicture' => [
'src' => null,
'sources' => [],
],
],
],
$this->manager->getEntityViewModels([$note])
);
}
public function testGenerateKey()
{
$menuName = 'application_menu';
$scope = new Scope();
ReflectionUtil::setId($scope, 1);
$this->assertEquals('application_menu_1', MenuUpdateUtils::generateKey($menuName, $scope));
}
public function testUpdateMenuItem()
{
$menu = $this->getMenu();
$item = $menu->getChild('item-1')
->getChild('item-1-1')
->getChild('item-1-1-1');
$firstLocalization = new Localization();
ReflectionUtil::setId($firstLocalization, 1);
$secondLocalization = new Localization();
ReflectionUtil::setId($secondLocalization, 2);
$update = new MenuUpdateStub();
$update->setKey('item-1-1-1');
$update->setParentKey('item-2');
$update->setUri('URI');
$update->addDescription(
(new LocalizedFallbackValue())
->setString('first test description')
->setLocalization($firstLocalization)
);
$update->addDescription(
(new LocalizedFallbackValue())
->setString('second test description')
->setLocalization($secondLocalization)
);
$update->setLinkAttributes(['testAttribute' => 'testValue']);
$expectedItem = $this->createItem('item-1-1-1');
$expectedItem->setParent($menu->getChild('item-2'));
$expectedItem->setUri('URI');
$expectedItem->setExtra('description', 'second test description');
$expectedItem->setLinkAttribute('testAttribute', 'testValue');
$localizationHelper = $this->createMock(LocalizationHelper::class);
$localizationHelper->expects($this->atLeastOnce())
->method('getCurrentLocalization')
->willReturn($secondLocalization);
MenuUpdateUtils::updateMenuItem($update, $menu, $localizationHelper);
$this->assertEquals($expectedItem, $item);
}
public function testGetTitle()
{
$this->controllerClassProvider->expects(self::once())
->method('getControllers')
->willReturn([
'test1_route' => [TestController::class, 'test1Action'],
'test2_route' => [TestController::class, 'test2Action'],
]);
$this->reader->expects(self::exactly(2))
->method('getMethodAnnotation')
->willReturnCallback(function (\ReflectionMethod $method, $annotationName) {
self::assertEquals(TitleTemplate::class, $annotationName);
if ($method->getName() === 'test1Action') {
return new TitleTemplate(['value' => 'test1 title']);
}
return null;
});
$this->assertEquals('test1 title', $this->annotationReader->getTitle('test1_route'));
$this->assertNull($this->annotationReader->getTitle('test2_route'));
$this->assertNull($this->annotationReader->getTitle('unknown_route'));
// test load data from cache file
ReflectionUtil::setPropertyValue($this->annotationReader, 'config', null);
$this->assertEquals('test1 title', $this->annotationReader->getTitle('test1_route'));
$this->assertNull($this->annotationReader->getTitle('test2_route'));
$this->assertNull($this->annotationReader->getTitle('unknown_route'));
}
private function createLocalization(string $name, int $id): Entity\Localization
{
$localization = new Entity\Localization();
$localization->setName($name);
ReflectionUtil::setId($localization, $id);
return $localization;
}
public function testClone(): void
{
$id = 123;
$value = new LocalizedFallbackValue();
ReflectionUtil::setId($value, $id);
$clonedValue = clone $value;
$this->assertEquals($id, $value->getId());
$this->assertNull($clonedValue->getId());
}
private function getLocalization(int $id, string $name): Localization
{
$localization = new Localization();
ReflectionUtil::setId($localization, $id);
$localization->setName($name);
return $localization;
}
public function voteDataProvider(): array
{
$localization = new Localization();
ReflectionUtil::setId($localization, 42);
$item = new Item();
ReflectionUtil::setId($item, 42);
return [
'abstain when not supported attribute' => [
'count' => null,
'default_localization' => 1,
'object' => $localization,
'attribute' => 'TEST',
'expected' => VoterInterface::ACCESS_ABSTAIN,
],
'abstain when not supported class' => [
'count' => null,
'default_localization' => 1,
'object' => $item,
'attribute' => 'DELETE',
'expected' => VoterInterface::ACCESS_ABSTAIN,
],
'abstain when new entity' => [
'count' => null,
'default_localization' => 1,
'object' => new Localization(),
'attribute' => 'DELETE',
'expected' => VoterInterface::ACCESS_ABSTAIN,
],
'abstain when more than one entity' => [
'count' => 2,
'default_localization' => 1,
'object' => $localization,
'attribute' => 'DELETE',
'expected' => VoterInterface::ACCESS_ABSTAIN,
],
'denied when count is 0' => [
'count' => 0,
'default_localization' => 1,
'object' => $localization,
'attribute' => 'DELETE',
'expected' => VoterInterface::ACCESS_DENIED,
],
'denied when count is 1' => [
'count' => 1,
'default_localization' => 1,
'object' => $localization,
'attribute' => 'DELETE',
'expected' => VoterInterface::ACCESS_DENIED,
],
'denied when localization used in config' => [
'count' => 2,
'default_localization' => 42,
'object' => $localization,
'attribute' => 'DELETE',
'expected' => VoterInterface::ACCESS_DENIED,
],
];
}
public function testRenderBlock()
{
$configManager = $this->createMock(ConfigManager::class);
$configManager->expects(self::once())
->method('get')
->with('oro_layout.debug_block_info')
->willReturn(true);
$this->twigRendererEngine->setConfigManager($configManager);
$view = $this->createMock(FormView::class);
$view->vars['cache_key'] = 'cache_key';
$template = $this->createMock(Template::class);
$template->expects($this->once())
->method('getTemplateName')
->willReturn('theme');
ReflectionUtil::setPropertyValue($this->twigRendererEngine, 'template', $template);
ReflectionUtil::setPropertyValue($this->twigRendererEngine, 'resources', ['cache_key' => []]);
$variables = ['id' => 'root'];
$result = array_merge(
$variables,
[
'attr' => [
'data-layout-debug-block-id' => 'root',
'data-layout-debug-block-template' => 'theme',
],
]
);
$this->environment->expects($this->once())
->method('mergeGlobals')
->with($result)
->willReturn([$template, 'root']);
$this->twigRendererEngine->renderBlock($view, [$template, 'root'], 'root', $variables);
}
public function eventDataProvider(): array
{
$newIntegration = new Integration();
$newOwner = $this->createMock(User::class);
$existingIntegration = new Integration();
ReflectionUtil::setId($existingIntegration, 100);
$someOwner = $this->createMock(User::class);
$existingIntegrationWithOwner = clone $existingIntegration;
$existingIntegrationWithOwner->setDefaultUserOwner($someOwner);
$integration = new Integration();
ReflectionUtil::setId($integration, 200);
return [
'new entity, should not dispatch' => [
$newIntegration,
$newOwner,
$integration,
false,
false,
],
'integration is not new, but owner existed before' => [
$existingIntegrationWithOwner,
$newOwner,
$integration,
false,
true,
],
'existing integration without owner, should dispatch' => [
$existingIntegration,
$newOwner,
$integration,
true,
true,
],
'should not dispatch if integration not found' => [
$existingIntegrationWithOwner,
$newOwner,
null,
false,
false,
],
];
}
public function testGetId()
{
$origin = new UserEmailOrigin();
ReflectionUtil::setId($origin, 123);
$this->assertEquals(123, $origin->getId());
}
public function testGetId()
{
$imapEmail = new ImapEmail();
ReflectionUtil::setId($imapEmail, 123);
$this->assertEquals(123, $imapEmail->getId());
}
public function testGetId(): void
{
$imapFolder = new ImapEmailFolder();
ReflectionUtil::setId($imapFolder, 123);
$this->assertEquals(123, $imapFolder->getId());
}
public function testOnUpdateAfter()
{
ReflectionUtil::setPropertyValue(
$this->configListener,
'featuresStates',
[
'feature1' => true,
'feature2' => false,
'feature3' => true,
]
);
ReflectionUtil::setPropertyValue(
$this->configListener,
'affectedFeatures',
[
'feature1',
'feature2',
'feature3',
]
);
$this->featureChecker->expects($this->any())
->method('isFeatureEnabled')
->willReturnMap([
['feature1', null, true],
['feature2', null, true],
['feature3', null, true],
]);
$this->featureChecker->expects($this->once())
->method('resetCache');
$this->eventDispatcher->expects($this->exactly(2))
->method('dispatch')
->withConsecutive(
[new FeaturesChange(['feature2' => true]), FeaturesChange::NAME],
[new FeatureChange('feature2', true), FeatureChange::NAME . '.feature2']
);
$this->configListener->onUpdateAfter();
}
private function getModel(int $id): FieldConfigModel
{
$model = new FieldConfigModel();
ReflectionUtil::setId($model, $id);
return $model;
}
/**
* @dataProvider dataProviderForMergeColumnOptions
*/
public function testMergeColumnOptions(array $existingOptions, array $newOptions, array $expectedOptions)
{
$objectKey = sprintf(ExtendOptionsManager::COLUMN_OPTION_FORMAT, 'test_table', 'test_column');
ReflectionUtil::setPropertyValue($this->manager, 'options', [$objectKey => $existingOptions]);
$this->manager->mergeColumnOptions('test_table', 'test_column', $newOptions);
$this->assertEquals([$objectKey => $expectedOptions], $this->manager->getExtendOptions());
}
private function getClassNames(SearchEntityConfigListener $listener): array
{
return ReflectionUtil::getPropertyValue($listener, 'classNames');
}
public function testShouldLogWarningIfInitializedPropertyOfEventManagerIsNotArray()
{
$logger = $this->createMock(LoggerInterface::class);
$metadataFactory = $this->createMock(OroClassMetadataFactory::class);
$em = $this->createMock(EntityManager::class);
$eventManager = new ContainerAwareEventManager($this->container);
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('getConfiguration')
->willReturn(new DbalConfiguration());
$connection->expects(self::once())
->method('isConnected')
->willReturn(true);
$connection->expects(self::once())
->method('close');
$em->expects(self::once())
->method('getConnection')
->willReturn($connection);
// guard
self::assertObjectHasAttribute('listeners', $eventManager);
self::assertObjectHasAttribute('initialized', $eventManager);
ReflectionUtil::setPropertyValue($eventManager, 'listeners', []);
ReflectionUtil::setPropertyValue($eventManager, 'initialized', new ArrayCollection());
$logger->expects(self::once())
->method('info')
->with('Disconnect ORM metadata factory');
$logger->expects(self::once())
->method('warning')
->with('The EventManager "listeners" and "initialized" properties should be an array');
$this->container->expects(self::once())
->method('initialized')
->with('foo_metadata_factory')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('foo_metadata_factory')
->willReturn($metadataFactory);
$metadataFactory->expects(self::once())
->method('isDisconnected')
->willReturn(false);
$metadataFactory->expects(self::once())
->method('getEntityManager')
->willReturn($em);
$em->expects(self::once())
->method('isOpen')
->willReturn(true);
$em->expects(self::any())
->method('getConfiguration')
->willReturn(new OrmConfiguration());
$em->expects(self::once())
->method('getEventManager')
->willReturn($eventManager);
$this->clearer->clear($logger);
}
public function testShouldLogWarningIfListenersPropertyOfEventManagerIsNotArray()
{
$logger = $this->createMock(LoggerInterface::class);
$metadataFactory = $this->createMock(OroClassMetadataFactory::class);
$em = $this->createMock(EntityManager::class);
$eventManager = new ContainerAwareEventManager($this->container);
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('getConfiguration')
->willReturn(new DbalConfiguration());
$connection->expects(self::once())
->method('isConnected')
->willReturn(true);
$connection->expects(self::once())
->method('close');
$em->expects(self::once())
->method('getConnection')
->willReturn($connection);
// guard
self::assertObjectHasAttribute('listeners', $eventManager);
self::assertObjectHasAttribute('initialized', $eventManager);
ReflectionUtil::setPropertyValue($eventManager, 'listeners', new ArrayCollection());
ReflectionUtil::setPropertyValue($eventManager, 'initialized', []);
$logger->expects(self::once())
->method('info')
->with('Disconnect ORM metadata factory');
$logger->expects(self::once())
->method('warning')
->with('The EventManager "listeners" and "initialized" properties should be an array');
$this->container->expects(self::once())
->method('initialized')
->with('foo_metadata_factory')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('foo_metadata_factory')
->willReturn($metadataFactory);
$metadataFactory->expects(self::once())
->method('isDisconnected')
->willReturn(false);
$metadataFactory->expects(self::once())
->method('getEntityManager')
->willReturn($em);
$em->expects(self::once())
->method('isOpen')
->willReturn(true);
$em->expects(self::any())
->method('getConfiguration')
->willReturn(new OrmConfiguration());
$em->expects(self::once())
->method('getEventManager')
->willReturn($eventManager);
$this->clearer->clear($logger);
}
public function testShouldRemoveUnneededListenersIfEventManagerIsInstanceOfContainerAwareEventManagerClass()
{
$logger = $this->createMock(LoggerInterface::class);
$metadataFactory = $this->createMock(OroClassMetadataFactory::class);
$em = $this->createMock(EntityManager::class);
$eventManager = new ContainerAwareEventManager($this->container);
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('getConfiguration')
->willReturn(new DbalConfiguration());
$connection->expects(self::once())
->method('isConnected')
->willReturn(true);
$connection->expects(self::once())
->method('close');
$em->expects(self::once())
->method('getConnection')
->willReturn($connection);
// guard
self::assertObjectHasAttribute('listeners', $eventManager);
self::assertObjectHasAttribute('initialized', $eventManager);
$eventManager->addEventListener(
[OrmEvents::onFlush, OrmEvents::loadClassMetadata, OrmEvents::onClassMetadataNotFound],
'foo_listener'
);
ReflectionUtil::setPropertyValue(
$eventManager,
'initialized',
[
OrmEvents::onFlush => true,
OrmEvents::loadClassMetadata => true,
OrmEvents::onClassMetadataNotFound => true,
]
);
$logger->expects(self::once())
->method('info')
->with('Disconnect ORM metadata factory');
$logger->expects(self::never())
->method('warning');
$this->container->expects(self::once())
->method('initialized')
->with('foo_metadata_factory')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('foo_metadata_factory')
->willReturn($metadataFactory);
$metadataFactory->expects(self::once())
->method('isDisconnected')
->willReturn(false);
$metadataFactory->expects(self::once())
->method('getEntityManager')
->willReturn($em);
$em->expects(self::once())
->method('isOpen')
->willReturn(true);
$em->expects(self::any())
->method('getConfiguration')
->willReturn(new OrmConfiguration());
$em->expects(self::once())
->method('getEventManager')
->willReturn($eventManager);
$this->clearer->clear($logger);
self::assertEquals(
[
OrmEvents::loadClassMetadata => ['_service_foo_listener' => 'foo_listener'],
OrmEvents::onClassMetadataNotFound => ['_service_foo_listener' => 'foo_listener'],
],
ReflectionUtil::getPropertyValue($eventManager, 'listeners')
);
self::assertEquals(
[
OrmEvents::loadClassMetadata => true,
OrmEvents::onClassMetadataNotFound => true,
],
ReflectionUtil::getPropertyValue($eventManager, 'initialized')
);
}
private function getFieldConfigModel(int $id): FieldConfigModel
{
$model = new FieldConfigModel();
ReflectionUtil::setId($model, $id);
return $model;
}
private function getFieldConfigModel(
?int $objectId,
?string $fieldName,
string $type,
array $scopes
): FieldConfigModel {
$model = new FieldConfigModel($fieldName, $type);
ReflectionUtil::setId($model, $objectId);
foreach ($scopes as $scope => $values) {
$model->fromArray($scope, $values);
}
return $model;
}
private function getEntityConfigModel(int $objectId, string $className): EntityConfigModel
{
$model = new EntityConfigModel($className);
ReflectionUtil::setId($model, $objectId);
return $model;
}
/**
* @inheritDoc
*/
protected function getExtensions(): array
{
$attributeMultiSelectType = new AttributeMultiSelectType($this->attributeManager, $this->getTranslator());
ReflectionUtil::setPropertyValue($attributeMultiSelectType, 'choices', self::ATTRIBUTES_CHOICES);
return [
new PreloadedExtension(
[
new LocalizedFallbackValueCollectionType($this->doctrine),
$attributeMultiSelectType,
new LocalizedPropertyType(),
new FallbackValueType(),
new FallbackPropertyType($this->createMock(TranslatorInterface::class)),
LocalizationCollectionType::class => new LocalizationCollectionTypeStub([
$this->getLocalization(self::LOCALIZATION_ID),
]),
],
[
FormType::class => [
new StripTagsExtensionStub($this),
new TooltipFormExtensionStub($this),
],
]
),
$this->getValidatorExtension(true),
];
}
/**
* @dataProvider addAttributesDataProvider
*/
public function testOnPreSubmit(array $fields, array $attributes, int $expectAdds)
{
$attributeFamilyId = 777;
$entity = $this->getEntityWithFamily();
$form = $this->getForm();
$form->expects($this->exactly($expectAdds))
->method('add');
ReflectionUtil::setPropertyValue($this->extension, 'fields', [get_class($entity) => $fields]);
$this->attributeManager->expects($this->once())
->method('getAttributesByFamily')
->with($entity->getAttributeFamily())
->willReturn($attributes);
$attributeFamilyRepository = $this->createMock(EntityRepository::class);
$attributeFamilyRepository->expects($this->once())
->method('find')
->with($attributeFamilyId)
->willReturn($entity->getAttributeFamily());
$this->doctrineHelper->expects($this->once())
->method('getEntityRepositoryForClass')
->with(AttributeFamily::class)
->willReturn($attributeFamilyRepository);
$event = new FormEvent($form, ['attributeFamily' => $attributeFamilyId]);
$this->extension->onPreSubmit($event);
}
/**
* @dataProvider addAttributesDataProvider
*/
public function testOnPreSetData(array $fields, array $attributes, int $expectAdds)
{
$entity = $this->getEntityWithFamily();
$form = $this->getForm();
ReflectionUtil::setPropertyValue($this->extension, 'fields', [get_class($entity) => $fields]);
$this->attributeManager->expects($this->once())
->method('getAttributesByFamily')
->with($entity->getAttributeFamily())
->willReturn($attributes);
$form->expects($this->any())
->method('has')
->willReturn(false);
$form->expects($this->exactly($expectAdds))
->method('add');
$event = new FormEvent($form, $entity);
$this->extension->onPreSetData($event);
}
private function getFieldConfigModel(int $id = null): FieldConfigModel
{
$entityConfigModel = new EntityConfigModel('class');
$fieldConfigModel = new FieldConfigModel('test', 'string');
ReflectionUtil::setId($fieldConfigModel, $id);
$fieldConfigModel->setEntity($entityConfigModel);
return $fieldConfigModel;
}
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function postSubmitWhenValidProvider(): array
{
$existingConfigModel = new EntityConfigModel('Entity\Test');
ReflectionUtil::setId($existingConfigModel, 1);
return [
'new model without trans (isValid=true)' => [
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
],
new EntityConfigModel('Entity\Test'),
[],
[
'label' => 'label_key',
'icon' => 'testIcon',
],
[
'label_key' => 'translated label',
],
],
'existing model without trans (isValid=true)' => [
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
],
$existingConfigModel,
[],
[
'label' => 'label_key',
'icon' => 'testIcon',
],
[
'label_key' => 'translated label',
],
],
'new model with trans (isValid=true)' => [
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
],
new EntityConfigModel('Entity\Test'),
[
'label_key' => 'translated label',
],
[
'label' => 'label_key',
'icon' => 'testIcon',
],
[
'label_key' => 'translated label',
],
],
'existing model with trans (isValid=true)' => [
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
],
$existingConfigModel,
[
'label_key' => 'translated label',
],
[
'label' => 'label_key',
'icon' => 'testIcon',
],
[],
],
'existing model with different trans (isValid=true)' => [
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
],
$existingConfigModel,
[
'label_key' => 'translated label 1',
],
[
'label' => 'label_key',
'icon' => 'testIcon',
],
[
'label_key' => 'translated label',
],
],
'existing model updated field' => [
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
'state' => 'Active',
],
],
$existingConfigModel,
[
'label_key' => 'translated label',
],
[
'label' => 'label_key',
'icon' => 'testIcon',
'state' => 'Active',
],
[],
],
];
}
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function preSetDataProvider(): array
{
$existingFieldConfigModel = new FieldConfigModel('testField', 'string');
ReflectionUtil::setId($existingFieldConfigModel, 1);
return [
'empty data (entity)' => [
[],
new EntityConfigModel('Entity\Test'),
[],
null,
],
'empty data (field)' => [
[],
new FieldConfigModel('testField', 'string'),
[],
null,
],
'new model without trans (entity)' => [
[
'entity' => [
'label' => 'testLabel',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
new EntityConfigModel('Entity\Test'),
[],
[
'entity' => [
'label' => '',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
],
'new model without trans (field)' => [
[
'entity' => [
'label' => 'testLabel',
],
'test' => [
'attr1' => 'testAttr',
],
],
new FieldConfigModel('testField', 'string'),
[],
[
'entity' => [
'label' => 'testField',
],
'test' => [
'attr1' => 'testAttr',
],
],
],
'existing model without trans (field)' => [
[
'entity' => [
'label' => 'testLabel',
],
'test' => [
'attr1' => 'testAttr',
],
],
$existingFieldConfigModel,
[],
[
'entity' => [
'label' => '',
],
'test' => [
'attr1' => 'testAttr',
],
],
],
'new model without translatable attributes (entity)' => [
[
'entity' => [
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
new EntityConfigModel('Entity\Test'),
[],
null,
],
'new model with trans (entity)' => [
[
'entity' => [
'label' => 'testLabel',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
new EntityConfigModel('Entity\Test'),
[
'testLabel' => 'translated label',
],
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
],
'new model with trans (field)' => [
[
'entity' => [
'label' => 'testLabel',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
new FieldConfigModel('testField', 'string'),
[
'testLabel' => 'translated label',
],
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
],
'existing model with trans (field)' => [
[
'entity' => [
'label' => 'testLabel',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
$existingFieldConfigModel,
[
'testLabel' => 'translated label',
],
[
'entity' => [
'label' => 'translated label',
'icon' => 'testIcon',
],
'test' => [
'attr1' => 'testAttr',
],
],
],
];
}
public function testOnPostFlushConfigShouldDoNothingForRestoredAttribute()
{
$entityClass = 'Test\Entity';
$fieldName = 'testField';
$fieldModelId = 123;
$entityModel = new EntityConfigModel($entityClass);
$fieldModel = new FieldConfigModel($fieldName);
$fieldModel->setEntity($entityModel);
ReflectionUtil::setId($fieldModel, $fieldModelId);
$fieldModel->fromArray('attribute', ['is_attribute' => true]);
$this->configManager->expects($this->once())
->method('getFieldConfigChangeSet')
->with('extend', $entityClass, $fieldName)
->willReturn(['is_deleted' => [true, false]]);
$this->doctrine->expects($this->never())
->method('getRepository');
$event = new PostFlushConfigEvent([$fieldModel], $this->configManager);
$this->listener->onPostFlushConfig($event);
}
public function testOnPostFlushConfigShouldDoNothingForRemovedField()
{
$entityClass = 'Test\Entity';
$fieldName = 'testField';
$fieldModelId = 123;
$entityModel = new EntityConfigModel($entityClass);
$fieldModel = new FieldConfigModel($fieldName);
$fieldModel->setEntity($entityModel);
ReflectionUtil::setId($fieldModel, $fieldModelId);
$this->configManager->expects($this->once())
->method('getFieldConfigChangeSet')
->with('extend', $entityClass, $fieldName)
->willReturn(['is_deleted' => [false, true]]);
$this->doctrine->expects($this->never())
->method('getRepository');
$event = new PostFlushConfigEvent([$fieldModel], $this->configManager);
$this->listener->onPostFlushConfig($event);
}
public function testOnPostFlushConfigShouldRemoveAttributeGroupRelationForRemovedAttribute()
{
$entityClass = 'Test\Entity';
$fieldName = 'testField';
$fieldModelId = 123;
$repository = $this->createMock(AttributeGroupRelationRepository::class);
$entityModel = new EntityConfigModel($entityClass);
$fieldModel = new FieldConfigModel($fieldName);
$fieldModel->setEntity($entityModel);
ReflectionUtil::setId($fieldModel, $fieldModelId);
$fieldModel->fromArray('attribute', ['is_attribute' => true]);
$this->configManager->expects($this->once())
->method('getFieldConfigChangeSet')
->with('extend', $entityClass, $fieldName)
->willReturn(['is_deleted' => [false, true]]);
$this->doctrine->expects($this->once())
->method('getRepository')
->with(AttributeGroupRelation::class)
->willReturn($repository);
$repository->expects($this->once())
->method('removeByFieldId')
->with($fieldModelId);
$event = new PostFlushConfigEvent([$fieldModel], $this->configManager);
$this->listener->onPostFlushConfig($event);
}
public function testPostFlush(): void
{
$emptyFamilyId = 1;
$filledFamilyId = 2;
$filledFamilyAttributeNames = ['name'];
$topicName = 'topic';
ReflectionUtil::setPropertyValue(
$this->listener,
'deletedAttributes',
[
$emptyFamilyId => [],
$filledFamilyId => $filledFamilyAttributeNames,
]
);
$this->listener->setTopic($topicName);
$this->messageProducer->expects(self::once())
->method('send')
->with(
$topicName,
new Message([
'attributeFamilyId' => $filledFamilyId,
'attributeNames' => $filledFamilyAttributeNames,
], MessagePriority::NORMAL)
);
$this->listener->postFlush();
self::assertEmpty(ReflectionUtil::getPropertyValue($this->listener, 'deletedAttributes'));
}
public function testIdGetter()
{
$obj = new ConfigModelIndexValue();
ReflectionUtil::setId($obj, 1);
$this->assertEquals(1, $obj->getId());
}
public function testThatEntityListAreLoadedAfterConfigurableEntityIsLoaded()
{
$entityModel0 = $this->createEntityModel('Test\ConfigurableEntity');
ReflectionUtil::setId($entityModel0, 123);
$entityModel1 = $this->createEntityModel(self::TEST_ENTITY);
$entityModel2 = $this->createEntityModel(self::TEST_ENTITY2);
$this->repo->expects($this->once())
->method('findOneBy')
->with(['className' => 'Test\ConfigurableEntity'])
->willReturn($entityModel0);
$query = $this->createMock(AbstractQuery::class);
$qb = $this->createMock(QueryBuilder::class);
$this->repo->expects($this->once())
->method('createQueryBuilder')
->with('e')
->willReturn($qb);
$qb->expects($this->once())
->method('where')
->with('e.id NOT IN (:exclusions)')
->willReturnSelf();
$qb->expects($this->once())
->method('setParameter')
->with('exclusions', [$entityModel0->getId()])
->willReturnSelf();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$query->expects($this->once())
->method('getResult')
->willReturn([$entityModel1, $entityModel2]);
$this->prepareCheckDetached(
[
UnitOfWork::STATE_MANAGED,
UnitOfWork::STATE_MANAGED,
UnitOfWork::STATE_MANAGED,
UnitOfWork::STATE_MANAGED,
]
);
$this->assertSame(
$entityModel0,
$this->configModelManager->findEntityModel('Test\ConfigurableEntity')
);
$this->assertEquals(
[$entityModel0, $entityModel1, $entityModel2],
$this->configModelManager->getModels()
);
// test localCache
$this->assertSame(
$entityModel0,
$this->configModelManager->findEntityModel('Test\ConfigurableEntity')
);
$this->assertSame(
$entityModel1,
$this->configModelManager->findEntityModel(self::TEST_ENTITY)
);
$this->assertSame(
$entityModel2,
$this->configModelManager->findEntityModel(self::TEST_ENTITY2)
);
}
public function testAttachmentEntityToModel()
{
$file = new File();
$file->setOriginalFilename('filename.txt');
$file->setFileSize(100);
$file->setMimeType('image/jpeg');
$attachment = new Attachment();
ReflectionUtil::setId($attachment, 1);
$attachment->setFile($file);
$attachment->setCreatedAt(new \DateTime('2015-04-13 19:09:32', new \DateTimeZone('UTC')));
$this->manager->expects($this->once())
->method('isImageType')
->willReturn(true);
$this->manager->expects($this->once())
->method('getAttachmentIconClass')
->willReturn('fa-class');
$this->manager->expects($this->once())
->method('getResizedImageUrl')
->willReturn('imageurl.jpg');
$attachmentModel = $this->emailAttachmentTransformer->attachmentEntityToModel($attachment);
$this->assertInstanceOf(EmailAttachmentModel::class, $attachmentModel);
$this->assertEquals(1, $attachmentModel->getId());
$this->assertEquals(100, $attachmentModel->getFileSize());
$this->assertEquals(
new \DateTime('2015-04-13 19:09:32', new \DateTimeZone('UTC')),
$attachmentModel->getModified()
);
$this->assertEquals(1, $attachmentModel->getType());
$this->assertEquals(null, $attachmentModel->getEmailAttachment());
$this->assertEquals('imageurl.jpg', $attachmentModel->getPreview());
$this->assertEquals('fa-class', $attachmentModel->getIcon());
$this->assertEquals('image/jpeg', $attachmentModel->getMimeType());
$this->assertEquals(100, $attachmentModel->getFileSize());
}
public function testSyncOrigins()
{
$container = $this->createMock(ContainerInterface::class);
$sync1 = $this->createMock(AbstractEmailSynchronizer::class);
$sync2 = $this->createMock(AbstractEmailSynchronizer::class);
$origin1 = new InternalEmailOrigin();
$origin1->setName('origin1');
ReflectionUtil::setId($origin1, 1);
$origin2 = new InternalEmailOrigin();
$origin2->setName('origin2');
ReflectionUtil::setId($origin2, 2);
$origin3 = new InternalEmailOrigin();
$origin3->setName('origin3');
ReflectionUtil::setId($origin3, 3);
$sync1->expects($this->exactly(3))
->method('supports')
->willReturnMap([
[$origin1, false],
[$origin2, true],
[$origin3, false],
]);
$sync1->expects($this->once())
->method('syncOrigins')
->with([2]);
$sync2->expects($this->exactly(3))
->method('supports')
->willReturnMap([
[$origin1, false],
[$origin2, false],
[$origin3, true],
]);
$sync2->expects($this->once())
->method('syncOrigins')
->with([3]);
$container->expects($this->any())
->method('get')
->willReturnMap([
['sync1', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $sync1],
['sync2', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $sync2],
]);
$manager = new EmailSynchronizationManager($container);
$manager->addSynchronizer('sync1');
$manager->addSynchronizer('sync2');
$manager->syncOrigins([$origin1, $origin2, $origin3]);
}
public function testSyncOneEmailBodyNotFound(): void
{
$email = new Email();
ReflectionUtil::setId($email, 123);
$email->setSubject('test email');
$emailUser = new EmailUser();
$user = new User();
$user->setId(43);
$organization = new Organization();
$organization->setId(44);
$origin = new TestEmailOrigin(789);
$origin->setActive(true);
$origin->setOwner($user);
$origin->setOrganization($organization);
$folder = new EmailFolder();
$folder->setOrigin($origin);
$origin->addFolder($folder);
$emailUser->setOrigin($origin);
$emailUser->addFolder($folder);
$email->addEmailUser($emailUser);
$exception = new EmailBodyNotFoundException($email);
$loader = $this->createMock(EmailBodyLoaderInterface::class);
$this->selector->expects(self::once())
->method('select')
->with($this->identicalTo($origin))
->willReturn($loader);
$loader->expects(self::once())
->method('loadEmailBody')
->willThrowException($exception);
$classMetadata = $this->createMock(ClassMetadataInfo::class);
$classMetadata->expects(self::once())
->method('getTableName')
->willReturn('oro_email');
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('update')
->with('oro_email', ['body_synced' => true], ['id' => 123]);
$this->em->expects(self::exactly(3))
->method('isOpen')
->willReturn(true);
$this->em->expects(self::once())
->method('getClassMetadata')
->with(Email::class)
->willReturn($classMetadata);
$this->em->expects(self::once())
->method('getConnection')
->willReturn($connection);
$this->logger->expects(self::once())
->method('notice')
->with(
'Attempt to load email body from remote server failed. Email id: 123.'
. ' Error: Cannot find a body for "test email" email.',
['exception' => $exception]
);
$this->logger->expects(self::never())
->method('warning');
$this->notificationAlertManager->expects(self::once())
->method('addNotificationAlert')
->willReturnCallback(function (NotificationAlertInterface $notificationAlert) {
self::assertEquals(
'Attempt to load email body failed. Error: Cannot find a body for "test email" email.',
$notificationAlert->toArray()['message']
);
return 'test_id';
});
$this->notificationAlertManager->expects(self::exactly(2))
->method('resolveNotificationAlertsByAlertTypeForUserAndOrganization');
$this->notificationAlertManager->expects(self::never())
->method('resolveNotificationAlertsByAlertTypeAndStepForUserAndOrganization');
$this->synchronizer->syncOneEmailBody($email);
}
public function testSyncOneEmailBodyFailure(): void
{
$email = new Email();
ReflectionUtil::setId($email, 123);
$email->setSubject('test email');
$emailUser = new EmailUser();
$user = new User();
$user->setId(34);
$organization = new Organization();
$organization->setId(33);
$origin = new TestEmailOrigin(456);
$origin->setActive(true);
$origin->setOwner($user);
$origin->setOrganization($organization);
$folder = new EmailFolder();
$folder->setOrigin($origin);
$origin->addFolder($folder);
$emailUser->setOrigin($origin);
$emailUser->addFolder($folder);
$email->addEmailUser($emailUser);
$exception = new \Exception('some exception');
$loader = $this->createMock(EmailBodyLoaderInterface::class);
$this->selector->expects(self::once())
->method('select')
->with($this->identicalTo($origin))
->willReturn($loader);
$loader->expects(self::once())
->method('loadEmailBody')
->willThrowException($exception);
$classMetadata = $this->createMock(ClassMetadataInfo::class);
$classMetadata->expects(self::once())
->method('getTableName')
->willReturn('oro_email');
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('update')
->with('oro_email', ['body_synced' => true], ['id' => 123]);
$this->em->expects(self::exactly(3))
->method('isOpen')
->willReturn(true);
$this->em->expects(self::once())
->method('getClassMetadata')
->with(Email::class)
->willReturn($classMetadata);
$this->em->expects(self::once())
->method('getConnection')
->willReturn($connection);
$this->logger->expects(self::once())
->method('info');
$this->notificationAlertManager->expects(self::once())
->method('addNotificationAlert')
->willReturnCallback(function (NotificationAlertInterface $notificationAlert) {
self::assertEquals(
'Load email body failed. Exception message:some exception',
$notificationAlert->toArray()['message']
);
return 'test_id';
});
$this->notificationAlertManager->expects(self::exactly(2))
->method('resolveNotificationAlertsByAlertTypeForUserAndOrganization');
$this->notificationAlertManager->expects(self::never())
->method('resolveNotificationAlertsByAlertTypeAndStepForUserAndOrganization');
$this->synchronizer->syncOneEmailBody($email);
}
public function testScheduleSyncOriginsJobShouldSendMessageToTopicWithIds(): void
{
ReflectionUtil::setPropertyValue($this->sync, 'messageQueueTopic', 'topic-name');
$producer = $this->createMock(MessageProducerInterface::class);
$producer->expects(self::once())
->method('send')
->with('topic-name', ['ids' => [1, 2, 3]]);
$this->sync->setMessageProducer($producer);
$this->sync->scheduleSyncOriginsJob([1, 2, 3]);
}
public function testScheduleSyncOriginsJobShouldThrowExceptionIfMessageProducerIsNotSet(): void
{
ReflectionUtil::setPropertyValue($this->sync, 'messageQueueTopic', 'topic-name');
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Message producer is not set');
$this->sync->scheduleSyncOriginsJob([1, 2, 3]);
}
private function getLocalization(int $id, Localization $parentLocalization = null): Localization
{
$localization = new Localization();
ReflectionUtil::setId($localization, $id);
if (null !== $parentLocalization) {
$localization->setParentLocalization($parentLocalization);
}
return $localization;
}
/**
* @dataProvider getDataProvider
*/
public function testGetData(?EntityMetadata $metadata, ?string $expected)
{
$activityList = $this->createMock(ActivityList::class);
$activityList->expects($this->once())
->method('getRelatedActivityId')
->willReturn(42);
$user = new User();
$this->entityNameResolver->expects($this->once())
->method('getName')
->with($user)
->willReturn('test name');
$emailAddress = new EmailAddress();
$emailAddress->setOwner($user);
$email = new Email();
ReflectionUtil::setId($email, 42);
$email->setSubject('test subject');
$email->setSentAt(new \DateTime('2018-03-23T11:43:15+00:00'));
$email->setFromEmailAddress($emailAddress);
$repository = $this->createMock(ObjectRepository::class);
$repository->expects($this->once())
->method('find')
->with(42)
->willReturn($email);
$em = $this->createMock(EntityManagerInterface::class);
$em->expects($this->once())
->method('getRepository')
->willReturn($repository);
$this->doctrineHelper->expects($this->once())
->method('getEntityManagerForClass')
->willReturn($em);
$this->configManager->expects($this->once())
->method('getEntityMetadata')
->with(User::class)
->willReturn($metadata);
$this->authorizationChecker->expects($this->any())
->method('isGranted')
->willReturn(true);
$this->urlGenerator->expects($this->any())
->method('generate')
->willReturn('test/user/link/1');
$this->assertEquals(
[
'ownerName' => 'test name',
'ownerLink' => $expected ? 'test/user/link/1' : null,
'entityId' => 42,
'headOwnerName' => 'test name',
'headSubject' => 'test subject',
'headSentAt' => '2018-03-23T11:43:15+00:00',
'isHead' => false,
'treadId' => null,
],
$this->emailActivityListProvider->getData($activityList)
);
}
private function prepareEmailUser(array $values, EmailOwnerInterface $user, bool $seen): EmailUser
{
$emailBody = new EmailBody();
$emailBody->setTextBody($values['getBodyContent']);
$email = new Email();
ReflectionUtil::setId($email, $values['getId']);
$email->setSubject($values['getSubject']);
$email->setFromName($values['getFromName']);
$emailAddress = new EmailAddress();
$emailAddress->setOwner($user);
$email->setFromEmailAddress($emailAddress);
$email->setEmailBody($emailBody);
$emailUser = new EmailUser();
$emailUser->setEmail($email);
$emailUser->setSeen($seen);
return $emailUser;
}
public function testShouldFilterOutEmailsWhichHasNoAutoResponse()
{
$email1 = new Email();
ReflectionUtil::setId($email1, 123);
$emailBody1 = new EmailBody();
$emailBody1->setEmail($email1);
$email2 = new Email();
ReflectionUtil::setId($email2, 12345);
$emailBody2 = new EmailBody();
$emailBody2->setEmail($email2);
ReflectionUtil::setPropertyValue($this->listener, 'emailBodies', [$emailBody1, $emailBody2]);
$this->autoResponseManager->expects($this->exactly(2))
->method('hasAutoResponses')
->willReturnOnConsecutiveCalls(false, true);
$this->producer->expects($this->once())
->method('send')
->with(SendAutoResponsesTopic::getName(), ['ids' => [12345]]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
}
public function testShouldFilterOutEmailsWhichHasNoAutoResponse()
{
$email1 = new Email();
ReflectionUtil::setId($email1, 123);
$emailBody1 = new EmailBody();
$emailBody1->setEmail($email1);
$email2 = new Email();
ReflectionUtil::setId($email2, 12345);
$emailBody2 = new EmailBody();
$emailBody2->setEmail($email2);
ReflectionUtil::setPropertyValue($this->listener, 'emailBodies', [$emailBody1, $emailBody2]);
$this->autoResponseManager->expects($this->exactly(2))
->method('hasAutoResponses')
->willReturnOnConsecutiveCalls(false, true);
$this->producer->expects($this->once())
->method('send')
->with(SendAutoResponsesTopic::getName(), ['ids' => [12345]]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
}
public function testShouldPublishEmailIdsIfTheyHasAutoResponse()
{
$this->autoResponseManager->expects($this->exactly(2))
->method('hasAutoResponses')
->willReturn(true);
$this->producer->expects($this->once())
->method('send')
->with(SendAutoResponsesTopic::getName(), ['ids' => [123, 12345]]);
$email1 = new Email();
ReflectionUtil::setId($email1, 123);
$emailBody1 = new EmailBody();
$emailBody1->setEmail($email1);
$email2 = new Email();
ReflectionUtil::setId($email2, 12345);
$emailBody2 = new EmailBody();
$emailBody2->setEmail($email2);
ReflectionUtil::setPropertyValue($this->listener, 'emailBodies', [$emailBody1, $emailBody2]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
}
public function testShouldPublishEmailIdsIfTheyHasAutoResponse()
{
$this->autoResponseManager->expects($this->exactly(2))
->method('hasAutoResponses')
->willReturn(true);
$this->producer->expects($this->once())
->method('send')
->with(SendAutoResponsesTopic::getName(), ['ids' => [123, 12345]]);
$email1 = new Email();
ReflectionUtil::setId($email1, 123);
$emailBody1 = new EmailBody();
$emailBody1->setEmail($email1);
$email2 = new Email();
ReflectionUtil::setId($email2, 12345);
$emailBody2 = new EmailBody();
$emailBody2->setEmail($email2);
ReflectionUtil::setPropertyValue($this->listener, 'emailBodies', [$emailBody1, $emailBody2]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
}
public function testIdGetter()
{
$entity = new Email();
ReflectionUtil::setId($entity, 1);
$this->assertEquals(1, $entity->getId());
}
public function testIdGetter()
{
$entity = new EmailRecipient();
ReflectionUtil::setId($entity, 1);
$this->assertEquals(1, $entity->getId());
}
public function testIdGetter()
{
$entity = new TestEmailOrigin();
ReflectionUtil::setId($entity, 1);
$this->assertEquals(1, $entity->getId());
}
public function testIdGetter()
{
$entity = new EmailFolder();
ReflectionUtil::setId($entity, 1);
$this->assertEquals(1, $entity->getId());
}
public function testIdGetter()
{
$entity = new EmailBody();
ReflectionUtil::setId($entity, 1);
$this->assertEquals(1, $entity->getId());
}
public function testIdGetter()
{
$entity = new EmailAttachment();
ReflectionUtil::setId($entity, 1);
$this->assertEquals(1, $entity->getId());
}
public function testIdGetter()
{
$entity = new EmailAttachmentContent();
ReflectionUtil::setId($entity, 1);
$this->assertEquals(1, $entity->getId());
}
private function getEmailUser(bool $private): EmailUser
{
$emailUser = new EmailUser();
ReflectionUtil::setId($emailUser, 123);
$emailUser->setIsEmailPrivate($private);
$email = new Email();
$email->addEmailUser($emailUser);
return $emailUser;
}
public function testExecute(): void
{
$entityMetadata = new EntityMetadata(DraftableEntityStub::class);
$entityMetadata->routes = ['update' => self::ROUTE_NAME];
$draftableEntity = new DraftableEntityStub();
ReflectionUtil::setId($draftableEntity, 1);
$this->configManager->expects($this->once())
->method('getEntityMetadata')
->willReturn($entityMetadata);
$context = new ActionData(['source' => $draftableEntity]);
$this->action->initialize(['source' => new PropertyPath('source'), 'route' => new PropertyPath('route')]);
$this->action->execute($context);
$expectedUrlRedirect = $this->contextAccessor->getValue($context, new PropertyPath('redirectUrl'));
$this->assertEquals(self::ROUTE_NAME, $expectedUrlRedirect);
}
/**
* @dataProvider normalizeFileOptionsDataProvider
*/
public function testNormalizeFileOptions(Options $allOptions, array $option, array $expectedOption): void
{
ReflectionUtil::setPropertyValue($allOptions, 'locked', true);
$this->assertEquals(
$expectedOption,
$this->extension->normalizeFileOptions($allOptions, $option)
);
}
private function setOwnershipFields(array $ownershipFields)
{
// set ownership fields
ReflectionUtil::setPropertyValue($this->extension, 'ownershipFields', $ownershipFields);
// skip load actions metadata
ReflectionUtil::setPropertyValue($this->extension, 'isMetadataVisited', true);
}
/**
* @dataProvider buildDatasourceProvider
*/
public function testBuildDatasource(
DatagridConfiguration $config,
array $dataSources,
?array $expectedException,
bool $processCallExpects = false
): void {
$builder = $this->getBuilder($dataSources);
$grid = $this->createMock(DatagridInterface::class);
foreach ($dataSources as $obj) {
if ($processCallExpects) {
$obj->expects($this->once())
->method('process')
->with($grid);
}
}
if ($expectedException !== null) {
[$name, $message] = $expectedException;
$this->expectException($name);
$this->expectExceptionMessage($message);
}
ReflectionUtil::callMethod($builder, 'buildDataSource', [$grid, $config]);
}
public function testToString()
{
ReflectionUtil::setId($this->object, 42);
self::assertSame('42', (string) $this->object);
}
public function testGetId()
{
self::assertNull($this->object->getId());
$testValue = 42;
ReflectionUtil::setId($this->object, $testValue);
self::assertEquals($testValue, $this->object->getId());
}
public function testCreatedAtGetter()
{
$date = new \DateTime('now');
$obj = new ConfigValue();
ReflectionUtil::setPropertyValue($obj, 'createdAt', $date);
$this->assertEquals($date, $obj->getCreatedAt());
}
public function testIdGetter()
{
$obj = new ConfigValue();
ReflectionUtil::setId($obj, 1);
$this->assertEquals(1, $obj->getId());
}
private function getDataMapping(ChartViewBuilder $builder): ?array
{
return ReflectionUtil::getPropertyValue($builder, 'dataMapping');
}
private function getDatagridColumnsDefinition(ChartViewBuilder $builder): array
{
return ReflectionUtil::getPropertyValue($builder, 'datagridColumnsDefinition');
}
private function getOptions(ChartViewBuilder $builder): array
{
return ReflectionUtil::getPropertyValue($builder, 'options');
}
private function getData(ChartViewBuilder $builder): DataInterface
{
return ReflectionUtil::getPropertyValue($builder, 'data');
}
private function createFile(): File
{
$file = new File();
ReflectionUtil::setId($file, 42);
$file->setFilename('test.jpg');
$file->setUuid('testuuid-uuid-uuid-testuuid');
return $file;
}
public function testPostFlush(): void
{
ReflectionUtil::setPropertyValue($this->listener, 'filesShouldBeDeleted', ['test', 'test1']);
$this->fileManager->expects(self::exactly(2))
->method('deleteFile')
->withConsecutive(['test'], ['test1']);
$this->logger->expects(self::never())
->method('warning');
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
self::assertEquals([], ReflectionUtil::getPropertyValue($this->listener, 'filesShouldBeDeleted'));
}
public function testPostFlushWithExceptionDuringDeletion(): void
{
$exception = new \Exception('Test exception.');
ReflectionUtil::setPropertyValue($this->listener, 'filesShouldBeDeleted', ['test']);
$this->fileManager->expects(self::once())
->method('deleteFile')
->with('test')
->willThrowException($exception);
$this->logger->expects(self::once())
->method('warning')
->with('Could not delete file "test"', ['exception' => $exception]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
self::assertEquals([], ReflectionUtil::getPropertyValue($this->listener, 'filesShouldBeDeleted'));
}
public function testOnFlush(): void
{
ReflectionUtil::setPropertyValue($this->listener, 'filesShouldBeDeleted', ['test']);
$this->listener->onFlush($this->createMock(OnFlushEventArgs::class));
self::assertEquals([], ReflectionUtil::getPropertyValue($this->listener, 'filesShouldBeDeleted'));
}
private function setFormViewData(FormInterface $form, $data): void
{
ReflectionUtil::setPropertyValue($form, 'defaultDataSet', true);
ReflectionUtil::setPropertyValue($form, 'viewData', $data);
}
public function testElapsedTimeForUpdatedEntity()
{
$entity = new AsyncOperation();
$entity->beforeSave();
// now - 5 min 10 sec
ReflectionUtil::setPropertyValue(
$entity,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT5M10S'))
);
$entity->preUpdate();
self::assertSame(310, $entity->getElapsedTime());
}
public function testId()
{
$entity = new AsyncOperation();
ReflectionUtil::setId($entity, 100);
self::assertEquals(100, $entity->getId());
}
private function getAsyncOperation(int $id): AsyncOperation
{
$operation = new AsyncOperation();
ReflectionUtil::setId($operation, $id);
return $operation;
}
public function testForRootJobLinkedToAsyncOperationUpdateInvalidProgress()
{
$job = new Job();
$job->setId(123);
$job->setData(['api_operation_id' => 1]);
$job->setStatus(Job::STATUS_RUNNING);
$job->setJobProgress(-1);
$operation = new AsyncOperation();
$operation->setJobId(123);
$operation->setStatus(AsyncOperation::STATUS_RUNNING);
// now - 10 min
ReflectionUtil::setPropertyValue(
$operation,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT10M'))
);
$operation->setProgress(0.5);
$this->em->expects(self::once())
->method('find')
->with(AsyncOperation::class, 1)
->willReturn($operation);
$this->uow->expects(self::never())
->method('recomputeSingleEntityChangeSet');
$this->listener->onBeforeSaveJob(new BeforeSaveJobEvent($job));
self::assertSame(0.5, $operation->getProgress());
}
public function testForRootJobLinkedToAsyncOperationUpdateZeroProgress()
{
$job = new Job();
$job->setId(123);
$job->setData(['api_operation_id' => 1]);
$job->setStatus(Job::STATUS_RUNNING);
$job->setJobProgress(0);
$operation = new AsyncOperation();
$operation->setJobId(123);
$operation->setStatus(AsyncOperation::STATUS_RUNNING);
// now - 10 min
ReflectionUtil::setPropertyValue(
$operation,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT10M'))
);
$operation->setProgress(0.5);
$classMetadata = $this->createMock(ClassMetadata::class);
$this->em->expects(self::once())
->method('find')
->with(AsyncOperation::class, 1)
->willReturn($operation);
$this->em->expects(self::once())
->method('getClassMetadata')
->with(AsyncOperation::class)
->willReturn($classMetadata);
$this->uow->expects(self::once())
->method('recomputeSingleEntityChangeSet')
->with(self::identicalTo($classMetadata), self::identicalTo($operation));
$this->listener->onBeforeSaveJob(new BeforeSaveJobEvent($job));
self::assertSame(0, $operation->getProgress());
}
public function testForRootJobLinkedToAsyncOperationUpdateProgress()
{
$job = new Job();
$job->setId(123);
$job->setData(['api_operation_id' => 1]);
$job->setStatus(Job::STATUS_RUNNING);
$job->setJobProgress(0.1); // 10%
$operation = new AsyncOperation();
$operation->setJobId(123);
$operation->setStatus(AsyncOperation::STATUS_RUNNING);
// now - 10 min
ReflectionUtil::setPropertyValue(
$operation,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT10M'))
);
$classMetadata = $this->createMock(ClassMetadata::class);
$this->em->expects(self::once())
->method('find')
->with(AsyncOperation::class, 1)
->willReturn($operation);
$this->em->expects(self::once())
->method('getClassMetadata')
->with(AsyncOperation::class)
->willReturn($classMetadata);
$this->uow->expects(self::once())
->method('recomputeSingleEntityChangeSet')
->with(self::identicalTo($classMetadata), self::identicalTo($operation));
$this->listener->onBeforeSaveJob(new BeforeSaveJobEvent($job));
self::assertSame(0.1, $operation->getProgress()); // 10%
}
public function testWithNotNewAddressEntity(): void
{
$address = new Address();
ReflectionUtil::setId($address, 123);
$constraint = new NewAddress();
$this->validator->validate($address, $constraint);
$this->buildViolation($constraint->message)
->assertRaised();
}
public function testMerge()
{
$account1 = new User();
$account2 = new User();
ReflectionUtil::setId($account1, 1);
ReflectionUtil::setId($account2, 2);
$entityMetadata = new EntityMetadata(['type' => ClassUtils::getRealClass($account1)]);
$entityData = new EntityData($entityMetadata, [$account1, $account2]);
$entityData->setMasterEntity($account1);
$fieldData = new FieldData($entityData, new FieldMetadata());
$fieldData->setMode(MergeModes::ACTIVITY_UNITE);
$query = $this->createMock(AbstractQuery::class);
$queryBuilder = $this->createMock(QueryBuilder::class);
$queryBuilder->expects($this->any())
->method('getQuery')
->willReturn($query);
$query->expects($this->any())
->method('getResult')
->willReturn([
['id' => 1, 'relatedActivityId' => 11],
['id' => 3, 'relatedActivityId' => 2],
]);
$repository = $this->createMock(ActivityListRepository::class);
$repository->expects($this->any())
->method('getActivityListQueryBuilderByActivityClass')
->willReturn($queryBuilder);
$repository->expects($this->any())
->method('findBy')
->willReturn([]);
$this->doctrineHelper->expects($this->any())
->method('getEntityRepository')
->willReturn($repository);
$this->activityListManager->expects($this->exactly(2))
->method('replaceActivityTargetWithPlainQuery');
$this->strategy->merge($fieldData);
}
public function testMerge()
{
$account1 = new User();
$account2 = new User();
ReflectionUtil::setId($account1, 1);
ReflectionUtil::setId($account2, 2);
$entityMetadata = new EntityMetadata(['type' => ClassUtils::getRealClass($account1)]);
$entityData = new EntityData($entityMetadata, [$account1, $account2]);
$entityData->setMasterEntity($account1);
$fieldData = new FieldData($entityData, new FieldMetadata());
$fieldData->setMode(MergeModes::ACTIVITY_REPLACE);
$fieldData->setSourceEntity($account2);
$query = $this->createMock(AbstractQuery::class);
$queryBuilder = $this->createMock(QueryBuilder::class);
$queryBuilder->expects($this->any())
->method('getQuery')
->willReturn($query);
$query->expects($this->any())
->method('getResult')
->willReturn([
['id' => 1, 'relatedActivityId' => 11],
['id' => 3, 'relatedActivityId' => 2],
]);
$repository = $this->createMock(ActivityListRepository::class);
$repository->expects($this->any())
->method('getActivityListQueryBuilderByActivityClass')
->willReturn($queryBuilder);
$repository->expects($this->any())
->method('findBy')
->willReturn([]);
$this->doctrineHelper->expects($this->any())
->method('getEntityRepository')
->willReturn($repository);
$this->activityListManager->expects($this->exactly(2))
->method('replaceActivityTargetWithPlainQuery');
$this->strategy->merge($fieldData);
}
protected function setUp(): void
{
$this->initClient();
$this->loadFixtures([
LoadActivityData::class,
]);
$this->authorizationChecker = $this->createMock(AuthorizationChecker::class);
$manager = self::getContainer()->get('oro_activity.manager.activity_context.api');
ReflectionUtil::setPropertyValue($manager, 'authorizationChecker', $this->authorizationChecker);
}
public function testGetTokenData()
{
$actionData = new ActionData([ActionData::OPERATION_TOKEN => 'test_key']);
$operation = $this->createMock(Operation::class);
$form = $this->createMock(FormInterface::class);
$formView = new FormView();
$tokenView = new FormView();
ReflectionUtil::setPropertyValue($formView, 'children', [FormProvider::CSRF_TOKEN_FIELD => $tokenView]);
$operation->expects($this->once())
->method('getName')
->willReturn('test_operation');
$form->expects($this->once())
->method('createView')
->willReturn($formView);
$options = ['csrf_token_id' => 'test_operation'];
$this->formFactory->expects($this->once())
->method('create')
->with($this->formType, $operation, $options)
->willReturn($form);
$result = $this->formProvider->createTokenData($operation, $actionData);
$this->assertArrayHasKey(OperationExecutionType::NAME, $result);
}
public function testReverseTransformForExistingAccount(): void
{
$accountId = 123;
$value = json_encode(['entityClass' => Account::class, 'entityId' => $accountId], JSON_THROW_ON_ERROR);
$account = new Account();
ReflectionUtil::setId($account, $accountId);
$customer = (new Customer())->setTarget($account);
$this->entityToStringTransformer->expects(self::once())
->method('reverseTransform')
->willReturn($account);
$this->accountCustomerManager->expects(self::once())
->method('getAccountCustomerByTarget')
->with(self::identicalTo($account))
->willReturn($customer);
/** @var Customer $result */
$result = $this->transformer->reverseTransform($value);
self::assertSame($customer, $result);
self::assertSame($account, $result->getAccount());
}
private function getB2bCustomer(int $id = null): B2bCustomer
{
$b2bCustomer = new B2bCustomer();
ReflectionUtil::setId($b2bCustomer, $id);
return $b2bCustomer;
}
private function getContactReason(int $id, string $defaultTitle): ContactReasonStub
{
$contactReason = new ContactReasonStub($defaultTitle);
ReflectionUtil::setId($contactReason, $id);
return $contactReason;
}
public function testPostFlush()
{
$this->em->expects(self::any())
->method('getRepository')
->with('OroChannelBundle:LifetimeValueHistory')
->willReturn($this->lifetimeRepo);
$account = $this->createMock(Account::class);
$channel = $this->createMock(Channel::class);
$channel->expects(self::any())
->method('getId')
->willReturn(1);
$account2 = clone $account;
$this->lifetimeRepo->expects(self::exactly(2))
->method('calculateAccountLifetime')
->with(
[Customer::class => 'lifetime'],
self::isInstanceOf(Account::class),
self::isInstanceOf(Channel::class)
)
->willReturnOnConsecutiveCalls(100, 200);
$this->em->expects(self::exactly(2))
->method('persist');
$this->em->expects(self::once())
->method('flush');
$channelDoctrineListener = new ChannelDoctrineListener($this->settingsProvider);
ReflectionUtil::setPropertyValue($channelDoctrineListener, 'queued', [
uniqid('accountId__channelId', true) => ['account' => $account, 'channel' => $channel],
uniqid('accountId__channelId', true) => ['account' => $account2, 'channel' => $channel],
]);
$channelDoctrineListener->postFlush(new PostFlushEventArgs($this->em));
}
public function testId()
{
$this->assertNull($this->comment->getId());
$value = 100;
ReflectionUtil::setId($this->comment, $value);
$this->assertEquals($value, $this->comment->getId());
}
public function testCloseOnSelfGeneratedIterator()
{
ReflectionUtil::setPropertyValue($this->reader, 'isSelfCreatedIterator', true);
$iterator = $this->createMock('\Iterator');
$this->reader->setSourceIterator($iterator);
$this->reader->close();
$this->assertNull($this->reader->getSourceIterator());
}
public function testGetId()
{
$this->assertNull($this->entity->getId());
$value = 8;
ReflectionUtil::setId($this->entity, $value);
$this->assertSame($value, $this->entity->getId());
}
private function getChannel(int $id, bool $enabled): Channel
{
$channel = new Channel();
ReflectionUtil::setId($channel, $id);
$channel->setEnabled($enabled);
return $channel;
}
private function getAuthorizeNetSettings(int $id): AuthorizeNetSettings
{
$settings = new AuthorizeNetSettings();
ReflectionUtil::setId($settings, $id);
return $settings;
}
private function getShoppingList(int $id): ShoppingList
{
$shoppingList = new ShoppingList();
ReflectionUtil::setId($shoppingList, $id);
return $shoppingList;
}
private function getProduct(int $id): Product
{
$product = new Product();
ReflectionUtil::setId($product, $id);
return $product;
}
public function testOnPostLoad()
{
$marketingList = new MarketingList();
ReflectionUtil::setId($marketingList, 1);
$this->event->expects($this->once())
->method('isDemoFixtures')
->willReturn(true);
$this->listenerManager->expects($this->once())
->method('enableListeners')
->with(self::LISTENERS);
$this->event->expects($this->once())
->method('log')
->with('updating marketing lists');
$this->entityProvider->expects($this->once())
->method('getEntities')
->with(false)
->willReturn([
['name' => Item::class],
]);
$this->event->expects($this->once())
->method('getObjectManager')
->willReturn($this->entityManager);
$this->entityManager->expects($this->once())
->method('getRepository')
->with(MarketingList::class)
->willReturn($this->entityRepository);
$this->entityRepository->expects($this->once())
->method('findBy')
->with([
'type' => 'dynamic',
'entity' => Item::class,
])
->willReturn([$marketingList]);
$event = new UpdateMarketingListEvent();
$event->setMarketingLists([$marketingList]);
$this->dispatcher->expects($this->once())
->method('dispatch')
->with($event, UpdateMarketingListProcessor::UPDATE_MARKETING_LIST_EVENT);
$this->listener->onPostLoad($this->event);
}
public function testGetId()
{
$this->assertNull($this->entity->getId());
$value = 42;
ReflectionUtil::setId($this->entity, $value);
$this->assertSame($value, $this->entity->getId());
}
public function testProcess()
{
$message = $this->createMock(MessageInterface::class);
$message->expects($this->any())
->method('getBody')
->willReturn(JSON::encode(['class' => Order::class]));
$marketingList = new MarketingList();
ReflectionUtil::setId($marketingList, 1);
$marketingList->setName('test');
$this->repository->expects($this->once())
->method('findBy')
->willReturn([$marketingList]);
$this->eventDispatcher->expects($this->once())
->method('dispatch')
->with(
$this->isInstanceOf(UpdateMarketingListEvent::class),
UpdateMarketingListProcessor::UPDATE_MARKETING_LIST_EVENT
);
$this->logger->expects($this->once())
->method('info');
$this->processor->process($message, $this->createMock(SessionInterface::class));
}
private function getCampaignCodeHistory(): CampaignCodeHistory
{
$campaign = new Campaign();
ReflectionUtil::setId($campaign, 1);
$campaignCodeHistory = new CampaignCodeHistory();
ReflectionUtil::setId($campaignCodeHistory, 1);
$campaignCodeHistory->setCode('test');
$campaignCodeHistory->setCampaign($campaign);
return $campaignCodeHistory;
}
public function testProcess()
{
$emailCampaignId = 1;
$emailCampaign = new EmailCampaign();
ReflectionUtil::setId($emailCampaign, $emailCampaignId);
$this->assertEmailCampaignFind($emailCampaign);
$session = $this->createMock(SessionInterface::class);
$message = $this->createMock(MessageInterface::class);
$message->expects($this->any())
->method('getBody')
->willReturn(JSON::encode(['email_campaign' => $emailCampaignId]));
$message->expects($this->any())
->method('getMessageId')
->willReturn('MID');
$this->logger->expects($this->never())
->method($this->anything());
$sender = $this->createMock(EmailCampaignSender::class);
$sender->expects($this->once())
->method('send');
$this->senderBuilder->expects($this->once())
->method('getSender')
->with($emailCampaign)
->willReturn($sender);
$job = $this->createMock(Job::class);
$this->jobRunner->expects($this->once())
->method('runUnique')
->willReturnCallback(function ($ownerId, $name, $closure) use ($job, $emailCampaignId) {
$this->assertEquals('MID', $ownerId);
$this->assertEquals(Topics::SEND_EMAIL_CAMPAIGN . ':' . $emailCampaignId, $name);
return $closure($this->jobRunner, $job);
});
$this->assertEquals(MessageProcessorInterface::ACK, $this->processor->process($message, $session));
}
private function getHasChangedSerializedFields(): array
{
return ReflectionUtil::getPropertyValue($this->listener, 'hasChangedSerializedFields');
}
private function setHasChangedSerializedFields(array $value): void
{
ReflectionUtil::setPropertyValue($this->listener, 'hasChangedSerializedFields', $value);
}
public function testNameIsUniqueForExistingClient()
{
$client = new Client();
ReflectionUtil::setId($client, 1);
$client->setName('test');
$client->setOwnerEntity('Test\OwnerEntity', 123);
$client->setOrganization($this->createMock(Organization::class));
$qb = $this->expectGetValidationQueryBuilder(
$client->getOrganization(),
$client->getName(),
$client->isFrontend(),
$client->getOwnerEntityClass(),
$client->getOwnerEntityId(),
$client->getId()
);
$query = $this->createMock(AbstractQuery::class);
$qb->expects(self::once())
->method('getQuery')
->willReturn($query);
$query->expects(self::once())
->method('getArrayResult')
->willReturn([]);
$this->validator->validate($client, new UniqueClientName());
$this->assertNoViolation();
}
public function testSubmitForExistingClient()
{
$client = new Client();
ReflectionUtil::setId($client, 1);
$client->setGrants(['grant1']);
$client->setOwnerEntity('Test\OwnerEntity', 123);
$submittedData = [
'name' => 'test name',
'active' => 1,
'grants' => 'grant2',
];
$this->organizationsProvider->expects(self::never())
->method('isMultiOrganizationSupported');
$this->organizationsProvider->expects(self::never())
->method('getClientOwnerOrganizations');
$this->organizationsProvider->expects(self::never())
->method('isOrganizationSelectorRequired');
$form = $this->createClientType($client, ['grant_types' => ['grant1', 'grant2']]);
$form->submit($submittedData);
self::assertTrue($form->isSynchronized());
self::assertTrue($form->isSubmitted());
self::assertFalse($form->has('organization'));
self::assertEquals('test name', $client->getName());
self::assertTrue($client->isActive());
self::assertEquals(['grant1'], $client->getGrants());
}
public function testGetId()
{
$entity = new Client();
self::assertNull($entity->getId());
$id = 123;
ReflectionUtil::setId($entity, $id);
self::assertSame($id, $entity->getId());
}
public function testGetId()
{
$entity = new AuthCode(
'test_id',
new \DateTime(),
['test_scope'],
$this->createMock(Client::class),
'test_user'
);
self::assertNull($entity->getId());
$id = 123;
ReflectionUtil::setId($entity, $id);
self::assertSame($id, $entity->getId());
}
public function testGetId()
{
$entity = new AccessToken(
'test_id',
new \DateTime(),
['test_scope'],
$this->createMock(Client::class),
'test_user'
);
self::assertNull($entity->getId());
$id = 123;
ReflectionUtil::setId($entity, $id);
self::assertSame($id, $entity->getId());
}
public function testExecuteAttemptsPassed()
{
$restClient = $this->createMock('RestClient\Client');
ReflectionUtil::setPropertyValue($this->client, 'restClient', $restClient);
ReflectionUtil::setPropertyValue($this->client, 'sleepBetweenAttempt', [0.1, 0.2, 0.3, 0.4]);
$request = $this->createMock('RestClient\Request');
$exceptionMessagePattern = 'Dotmailer REST client exception:' . PHP_EOL .
'[exception type] Exception' . PHP_EOL .
'[exception message] %s' . PHP_EOL .
'[request url] testCall' . PHP_EOL .
'[request method] ' . PHP_EOL .
'[request data] ' . PHP_EOL .
'[response code] ' . PHP_EOL .
'[response body] ';
$this->logger->expects($this->exactly(6))
->method('warning')
->withConsecutive(
[
'[Warning] Attempt failed. Error message:' . PHP_EOL .
sprintf($exceptionMessagePattern, 'Exception A'),
],
['[Warning] Attempt number 1 with 0.1 sec delay.'],
[
'[Warning] Attempt failed. Error message:' . PHP_EOL .
sprintf($exceptionMessagePattern, 'Exception B'),
],
['[Warning] Attempt number 2 with 0.2 sec delay.'],
[
'[Warning] Attempt failed. Error message:' . PHP_EOL .
sprintf($exceptionMessagePattern, 'Exception C'),
],
['[Warning] Attempt number 3 with 0.3 sec delay.']
);
$restClient->expects($this->exactly(4))
->method('newRequest')
->willReturnOnConsecutiveCalls(
new ReturnCallback(function () {
throw new \Exception('Exception A');
}),
new ReturnCallback(function () {
throw new \Exception('Exception B');
}),
new ReturnCallback(function () {
throw new \Exception('Exception C');
}),
$request
);
$request->expects($this->once())
->method('getResponse')
->will($this->returnValue($this->response));
$this->response->expects($this->once())
->method('getInfo')
->will($this->returnValue($this->info));
$this->info->http_code = 200;
$expectedResult = 'Some result';
$this->response->expects($this->once())
->method('getParsedResponse')
->will($this->returnValue($expectedResult));
$this->assertEquals($expectedResult, $this->client->execute('testCall'));
}
/**
* @dataProvider executeAttemptsFailedDataProvider
*/
public function testExecuteAttemptsFailed(string $responseBody, string $responseCode, string $expectedMessage)
{
$exceptionMessage = 'Dotmailer REST client exception:' . PHP_EOL .
'[exception type] Oro\Bundle\DotmailerBundle\Exception\RestClientAttemptException' . PHP_EOL .
'[exception message] ' . $expectedMessage . PHP_EOL .
'[request url] testCall' . PHP_EOL .
'[request method] ' . PHP_EOL .
'[request data] ' . PHP_EOL .
'[response code] ' . $responseCode . PHP_EOL .
'[response body] ' . $responseBody;
$this->expectException(\Oro\Bundle\DotmailerBundle\Exception\RestClientException::class);
$this->expectExceptionMessage($exceptionMessage);
$restClient = $this->createMock('RestClient\Client');
ReflectionUtil::setPropertyValue($this->client, 'restClient', $restClient);
ReflectionUtil::setPropertyValue($this->client, 'sleepBetweenAttempt', [0.1, 0.2, 0.3, 0.4]);
$request = $this->createMock('RestClient\Request');
$restClient->expects($this->exactly(5))
->method('newRequest')
->will($this->returnValue($request));
$request->expects($this->exactly(5))
->method('getResponse')
->will($this->returnValue($this->response));
$this->response->expects($this->exactly(5))
->method('getInfo')
->will($this->returnValue($this->info));
$this->info->http_code = $responseCode;
$this->response->expects($this->exactly(5))
->method('getParsedResponse')
->will($this->returnValue($responseBody));
$this->logger->expects($this->exactly(8))
->method('warning')
->withConsecutive(
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 1 with 0.1 sec delay.'],
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 2 with 0.2 sec delay.'],
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 3 with 0.3 sec delay.'],
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 4 with 0.4 sec delay.']
);
$this->client->execute('testCall');
}
protected function initClient()
{
$restClient = $this->createMock('\RestClient\Client');
ReflectionUtil::setPropertyValue($this->client, 'restClient', $restClient);
$request = $this->createMock('\RestClient\Request');
$restClient->expects($this->once())
->method('newRequest')
->will($this->returnValue($request));
$request->expects($this->once())
->method('getResponse')
->will($this->returnValue($this->response));
$this->response->expects($this->once())
->method('getInfo')
->will($this->returnValue($this->info));
}
public function testDataWithEntityId()
{
$entity = new Task();
ReflectionUtil::setId($entity, 1);
$request = new Request();
$this->router->expects($this->once())
->method('generate')
->with('oro_task_update', ['id' => 1])
->willReturn('/update/1');
$formView = $this->createMock(FormView::class);
$form = $this->createMock(FormInterface::class);
$form->expects($this->any())
->method('createView')
->willReturn($formView);
$result = $this->provider->getData($entity, $form, $request);
self::assertArrayHasKey('entity', $result);
self::assertEquals($entity, $result['entity']);
self::assertArrayHasKey('form', $result);
self::assertEquals($formView, $result['form']);
self::assertArrayHasKey('formAction', $result);
self::assertEquals('/update/1', $result['formAction']);
}
public function testProcessGetRequestWithTargetEntity()
{
ReflectionUtil::setId($this->entity, 123);
$targetEntity = new TestTarget(123);
$targetEntity1 = new TestTarget(456);
$this->request->query->set('entityClass', get_class($targetEntity));
$this->request->query->set('entityId', $targetEntity->getId());
$this->phoneProvider->expects($this->never())
->method('getPhoneNumber');
$this->phoneProvider->expects($this->once())
->method('getPhoneNumbers')
->with($this->identicalTo($targetEntity))
->willReturn([
['phone1', $targetEntity],
['phone2', $targetEntity],
['phone1', $targetEntity1],
]);
$this->entityRoutingHelper->expects($this->once())
->method('getEntity')
->with(get_class($targetEntity), $targetEntity->getId())
->willReturn($targetEntity);
$this->formFactory->expects($this->once())
->method('createNamed')
->with(
'oro_call_form',
'oro_call_form',
$this->entity,
[
'phone_suggestions' => ['phone1', 'phone2'],
]
)
->willReturn($this->form);
$this->form->expects($this->never())
->method('submit');
$this->assertFalse($this->handler->process($this->entity));
}
public function testProcessWithContexts()
{
$context = new User();
ReflectionUtil::setId($context, 123);
$owner = new User();
ReflectionUtil::setId($owner, 321);
$this->entity->setOwner($owner);
$this->request->initialize([], self::FORM_DATA);
$this->request->setMethod('POST');
$this->formFactory->expects($this->once())
->method('createNamed')
->with('oro_call_form', 'oro_call_form', $this->entity, [])
->willReturn($this->form);
$this->form->expects($this->any())
->method('get')
->willReturn($this->form);
$this->form->expects($this->any())
->method('has')
->willReturn(true);
$this->form->expects($this->once())
->method('isValid')
->willReturn(true);
$this->form->expects($this->once())
->method('setData')
->with($this->identicalTo($this->entity));
$this->form->expects($this->any())
->method('getData')
->willReturn([$context]);
$this->activityManager->expects($this->never())
->method('removeActivityTarget');
$this->activityManager->expects($this->once())
->method('setActivityTargets')
->with(
$this->identicalTo($this->entity),
$this->identicalTo([$context, $owner])
);
$this->assertTrue(
$this->handler->process($this->entity)
);
}
private function getChannel(bool $isTwoWaySyncEnabled): Channel
{
$synchronizationSettings = $this->createMock(ConfigObject::class);
$synchronizationSettings->expects($this->once())
->method('offsetGetOr')
->with('isTwoWaySyncEnabled', false)
->willReturn($isTwoWaySyncEnabled);
$channel = new Channel();
ReflectionUtil::setId($channel, 123);
$channel->setSynchronizationSettings($synchronizationSettings);
return $channel;
}
private function getCalendarEntity(int $id): Calendar
{
$calendar = new Calendar();
ReflectionUtil::setId($calendar, $id);
return $calendar;
}
public function testValidateWithErrorsWorksCorrectlyIfCalendarFieldDataIsInteger()
{
$expectedCalendarId = 42;
$expectedCalendarAlias = 'alias';
$calendarField = $this->prepareFormStub([], [], $expectedCalendarId);
$calendarAliasField = $this->prepareFormStub([], [], $expectedCalendarAlias);
$form = $this->prepareFormStub(
[['calendar', true], ['calendarAlias', true]],
[['calendar', $calendarField], ['calendarAlias', $calendarAliasField]]
);
$this->calendarEventManager->expects($this->once())
->method('getCalendarUid')
->with($expectedCalendarAlias, $expectedCalendarId)
->willReturn('unique_calendar_uid');
$calendarEvent = new CalendarEvent();
$recurringEvent = new CalendarEvent();
$recurringEvent->setRecurrence(new Recurrence());
ReflectionUtil::setId($calendarEvent, 123);
$calendarEvent->setRecurringEvent($recurringEvent);
$constraint = new RecurringCalendarEventException();
$this->setRoot($form);
$this->validator->validate($calendarEvent, $constraint);
/**
* Check validation message was added in case if Recurring event Calendar is different from
* main event calendar
*/
$this->buildViolation($constraint->cantChangeCalendarMessage)
->assertRaised();
}
public function testValidateWithErrorsWorksCorrectlyIfCalendarFieldDataIsCalendarEntityObject()
{
$calendar = new Calendar();
$expectedCalendarId = 42;
$expectedCalendarAlias = 'alias';
ReflectionUtil::setId($calendar, $expectedCalendarId);
$calendarField = $this->prepareFormStub([], [], $calendar);
$calendarAliasField = $this->prepareFormStub([], [], $expectedCalendarAlias);
$form = $this->prepareFormStub(
[['calendar', true], ['calendarAlias', true]],
[['calendar', $calendarField], ['calendarAlias', $calendarAliasField]]
);
/**
* Check Calendar entity Id passed to getCalendarUid to match method's contract
*/
$this->calendarEventManager->expects($this->once())
->method('getCalendarUid')
->with($expectedCalendarAlias, $expectedCalendarId)
->willReturn('unique_calendar_uid');
$calendarEvent = new CalendarEvent();
$recurringEvent = new CalendarEvent();
$recurringEvent->setRecurrence(new Recurrence());
ReflectionUtil::setId($calendarEvent, 123);
$calendarEvent->setRecurringEvent($recurringEvent);
$constraint = new RecurringCalendarEventException();
$this->setRoot($form);
$this->validator->validate($calendarEvent, $constraint);
/**
* Check validation message was added in case if Recurring event Calendar is different from
* main event calendar
*/
$this->buildViolation($constraint->cantChangeCalendarMessage)
->assertRaised();
}
public function testValidateWithErrors()
{
$calendarEvent = new CalendarEvent();
$recurringEvent = new CalendarEvent();
ReflectionUtil::setId($recurringEvent, 123);
ReflectionUtil::setId($calendarEvent, 123);
$calendarEvent->setRecurringEvent($recurringEvent);
$constraint = new RecurringCalendarEventException();
$this->validator->validate($calendarEvent, $constraint);
$this
->buildViolation($constraint->selfRelationMessage)
->buildNextViolation($constraint->wrongRecurrenceMessage)
->assertRaised();
}
private function getCalendarEventAttendeeEntity(int $id, string $email): Attendee
{
$attendee = new Attendee();
ReflectionUtil::setId($attendee, $id);
$attendee->setEmail($email);
return $attendee;
}
private function getCalendarEventEntity(int $id): CalendarEvent
{
$calendarEvent = new CalendarEvent();
ReflectionUtil::setId($calendarEvent, $id);
return $calendarEvent;
}
public function testGetCalendarDefaultValues()
{
$organizationId = 1;
$userId = 123;
$calendarId = 20;
$calendarIds = [10, 20];
$calendar1 = new Calendar();
ReflectionUtil::setId($calendar1, $calendarIds[0]);
$user1 = new User();
ReflectionUtil::setId($user1, $userId);
$calendar1->setOwner($user1);
$calendar2 = new Calendar();
ReflectionUtil::setId($calendar2, $calendarIds[1]);
$user2 = new User();
ReflectionUtil::setId($user2, 456);
$calendar2->setOwner($user2);
$calendars = [$calendar1, $calendar2];
$qb = $this->createMock(QueryBuilder::class);
$repo = $this->createMock(EntityRepository::class);
$repo->expects($this->once())
->method('createQueryBuilder')
->with('o')
->willReturn($qb);
$this->doctrineHelper->expects($this->once())
->method('getEntityRepository')
->with('OroCalendarBundle:Calendar')
->willReturn($repo);
$qb->expects($this->once())
->method('select')
->with('o, owner')
->willReturnSelf();
$qb->expects($this->once())
->method('innerJoin')
->with('o.owner', 'owner')
->willReturnSelf();
$qb->expects($this->once())
->method('expr')
->willReturn(new Expr());
$qb->expects($this->once())
->method('where')
->with(new Expr\Func('o.id IN', [':calendarIds']))
->willReturnSelf();
$query = $this->createMock(AbstractQuery::class);
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$query->expects($this->once())
->method('getResult')
->willReturn($calendars);
$this->entityNameResolver->expects($this->exactly(2))
->method('getName')
->withConsecutive(
[$this->identicalTo($user1)],
[$this->identicalTo($user2)]
)
->willReturnOnConsecutiveCalls(
'John Doo',
'John Smith'
);
$result = $this->provider->getCalendarDefaultValues($organizationId, $userId, $calendarId, $calendarIds);
$this->assertEquals(
[
$calendarIds[0] => [
'calendarName' => 'John Doo',
'userId' => $userId,
],
$calendarIds[1] => [
'calendarName' => 'John Smith',
'userId' => 456,
'removable' => false,
'canAddEvent' => true,
'canEditEvent' => true,
'canDeleteEvent' => true,
],
],
$result
);
}
public function testGetCalendarDefaultValuesCanAddEvents()
{
$organizationId = 1;
$userId = 123;
$calendarId = 10;
$calendarIds = [10];
$calendar1 = new SystemCalendar();
ReflectionUtil::setId($calendar1, 1);
$organization1 = new Organization();
$calendar1->setOrganization($organization1);
$calendar1->setName('Main OroCRM');
$calendar1->setBackgroundColor('#FF0000');
$calendars = [$calendar1];
$this->calendarConfig->expects($this->once())
->method('isSystemCalendarEnabled')
->willReturn(true);
$this->authorizationChecker->expects($this->once())
->method('isGranted')
->with('oro_system_calendar_management')
->willReturn(true);
$repo = $this->createMock(SystemCalendarRepository::class);
$query = $this->createMock(AbstractQuery::class);
$qb = $this->createMock(QueryBuilder::class);
$repo->expects($this->once())
->method('getSystemCalendarsQueryBuilder')
->with($organizationId)
->willReturn($qb);
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$query->expects($this->once())
->method('getResult')
->willReturn($calendars);
$this->doctrineHelper->expects($this->once())
->method('getEntityRepository')
->with('OroCalendarBundle:SystemCalendar')
->willReturn($repo);
$result = $this->provider->getCalendarDefaultValues($organizationId, $userId, $calendarId, $calendarIds);
$this->assertEquals(
[
$calendar1->getId() => [
'calendarName' => $calendar1->getName(),
'backgroundColor' => $calendar1->getBackgroundColor(),
'removable' => false,
'position' => -60,
'canAddEvent' => true,
'canEditEvent' => true,
'canDeleteEvent' => true,
],
],
$result
);
}
public function testGetCalendarDefaultValuesCannotAddEvents()
{
$organizationId = 1;
$userId = 123;
$calendarId = 10;
$calendarIds = [10, 20];
$calendar1 = new SystemCalendar();
ReflectionUtil::setId($calendar1, 1);
$organization1 = new Organization();
$calendar1->setOrganization($organization1);
$calendar1->setName('Main OroCRM');
$calendar1->setBackgroundColor('#FF0000');
$calendar2 = new SystemCalendar();
ReflectionUtil::setId($calendar2, 2);
$calendar2->setOrganization($organization1);
$calendar2->setName('Second OroCRM');
$calendars = [$calendar1, $calendar2];
$this->calendarConfig->expects($this->once())
->method('isSystemCalendarEnabled')
->willReturn(true);
$this->authorizationChecker->expects($this->once())
->method('isGranted')
->with('oro_system_calendar_management')
->willReturn(false);
$repo = $this->createMock(SystemCalendarRepository::class);
$query = $this->createMock(AbstractQuery::class);
$qb = $this->createMock(QueryBuilder::class);
$repo->expects($this->once())
->method('getSystemCalendarsQueryBuilder')
->with($organizationId)
->willReturn($qb);
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$query->expects($this->once())
->method('getResult')
->willReturn($calendars);
$this->doctrineHelper->expects($this->once())
->method('getEntityRepository')
->with('OroCalendarBundle:SystemCalendar')
->willReturn($repo);
$result = $this->provider->getCalendarDefaultValues($organizationId, $userId, $calendarId, $calendarIds);
$this->assertEquals(
[
$calendar1->getId() => [
'calendarName' => $calendar1->getName(),
'backgroundColor' => $calendar1->getBackgroundColor(),
'removable' => false,
'position' => -60,
],
$calendar2->getId() => [
'calendarName' => $calendar2->getName(),
'backgroundColor' => $calendar2->getBackgroundColor(),
'removable' => false,
'position' => -60,
],
],
$result
);
}
public function testGetCalendarDefaultValuesCanAddEvents()
{
$organizationId = 1;
$userId = 123;
$calendarId = 10;
$calendarIds = [10];
$calendar1 = new SystemCalendar();
ReflectionUtil::setId($calendar1, 1);
$calendar1->setName('Master');
$calendar1->setBackgroundColor('#FF0000');
$calendars = [$calendar1];
$this->calendarConfig->expects($this->once())
->method('isPublicCalendarEnabled')
->willReturn(true);
$this->authorizationChecker->expects($this->once())
->method('isGranted')
->with('oro_public_calendar_management')
->willReturn(true);
$repo = $this->createMock(SystemCalendarRepository::class);
$query = $this->createMock(AbstractQuery::class);
$qb = $this->createMock(QueryBuilder::class);
$repo->expects($this->once())
->method('getPublicCalendarsQueryBuilder')
->willReturn($qb);
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$query->expects($this->once())
->method('getResult')
->willReturn($calendars);
$this->doctrineHelper->expects($this->once())
->method('getEntityRepository')
->with('OroCalendarBundle:SystemCalendar')
->willReturn($repo);
$result = $this->provider->getCalendarDefaultValues($organizationId, $userId, $calendarId, $calendarIds);
$this->assertEquals(
[
$calendar1->getId() => [
'calendarName' => $calendar1->getName(),
'backgroundColor' => $calendar1->getBackgroundColor(),
'removable' => false,
'position' => -80,
'canAddEvent' => true,
'canEditEvent' => true,
'canDeleteEvent' => true,
],
],
$result
);
}
public function testGetCalendarDefaultValuesCannotAddEvents()
{
$organizationId = 1;
$userId = 123;
$calendarId = 10;
$calendarIds = [10];
$calendar1 = new SystemCalendar();
ReflectionUtil::setId($calendar1, 1);
$calendar1->setName('Master');
$calendar1->setBackgroundColor('#FF0000');
$calendars = [$calendar1];
$this->calendarConfig->expects($this->once())
->method('isPublicCalendarEnabled')
->willReturn(true);
$repo = $this->createMock(SystemCalendarRepository::class);
$query = $this->createMock(AbstractQuery::class);
$qb = $this->createMock(QueryBuilder::class);
$repo->expects($this->once())
->method('getPublicCalendarsQueryBuilder')
->willReturn($qb);
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$query->expects($this->once())
->method('getResult')
->willReturn($calendars);
$this->doctrineHelper->expects($this->once())
->method('getEntityRepository')
->with('OroCalendarBundle:SystemCalendar')
->willReturn($repo);
$result = $this->provider->getCalendarDefaultValues($organizationId, $userId, $calendarId, $calendarIds);
$this->assertEquals(
[
$calendar1->getId() => [
'calendarName' => $calendar1->getName(),
'backgroundColor' => $calendar1->getBackgroundColor(),
'removable' => false,
'position' => -80,
],
],
$result
);
}
public function testSetPublicCalendar()
{
$calendarId = 123;
$calendar = new SystemCalendar();
$calendar->setPublic(true);
ReflectionUtil::setId($calendar, $calendarId);
$event = new CalendarEvent();
$this->calendarConfig->expects($this->once())
->method('isPublicCalendarEnabled')
->willReturn(true);
$repo = $this->createMock(SystemCalendarRepository::class);
$this->doctrine->expects($this->once())
->method('getRepository')
->with('OroCalendarBundle:SystemCalendar')
->willReturn($repo);
$repo->expects($this->once())
->method('find')
->with($calendarId)
->willReturn($calendar);
$this->manager->setCalendar($event, SystemCalendar::PUBLIC_CALENDAR_ALIAS, $calendarId);
$this->assertSame($calendar, $event->getSystemCalendar());
}
public function testSetSystemCalendar()
{
$calendarId = 123;
$calendar = new SystemCalendar();
$calendar->setPublic(false);
ReflectionUtil::setId($calendar, $calendarId);
$event = new CalendarEvent();
$this->calendarConfig->expects($this->once())
->method('isSystemCalendarEnabled')
->willReturn(true);
$repo = $this->createMock(SystemCalendarRepository::class);
$this->doctrine->expects($this->once())
->method('getRepository')
->with('OroCalendarBundle:SystemCalendar')
->willReturn($repo);
$repo->expects($this->once())
->method('find')
->with($calendarId)
->willReturn($calendar);
$this->manager->setCalendar($event, SystemCalendar::CALENDAR_ALIAS, $calendarId);
$this->assertSame($calendar, $event->getSystemCalendar());
}
public function testSetSameUserCalendar()
{
$calendarId = 123;
$calendar = new Calendar();
ReflectionUtil::setId($calendar, $calendarId);
$event = new CalendarEvent();
$event->setCalendar($calendar);
$this->doctrine->expects($this->never())
->method('getRepository');
$this->manager->setCalendar($event, Calendar::CALENDAR_ALIAS, $calendarId);
$this->assertSame($calendar, $event->getCalendar());
}
public function testSetUserCalendar()
{
$calendarId = 123;
$calendar = new Calendar();
ReflectionUtil::setId($calendar, $calendarId);
$event = new CalendarEvent();
$repo = $this->createMock(CalendarRepository::class);
$this->doctrine->expects($this->once())
->method('getRepository')
->with('OroCalendarBundle:Calendar')
->willReturn($repo);
$repo->expects($this->once())
->method('find')
->with($calendarId)
->willReturn($calendar);
$this->manager->setCalendar($event, Calendar::CALENDAR_ALIAS, $calendarId);
$this->assertSame($calendar, $event->getCalendar());
}
public function testSubmitValidData()
{
$formData = [
'targetCalendar' => 1,
'calendarAlias' => 'testCalendarAlias',
'calendar' => 2,
'position' => 100,
'visible' => true,
'backgroundColor' => '#00FF00',
];
$form = $this->factory->create(CalendarPropertyApiType::class);
$form->submit($formData);
$this->assertTrue($form->isSynchronized());
/** @var CalendarProperty $result */
$result = $form->getData();
$this->assertInstanceOf(CalendarProperty::class, $result);
$calendar = new Calendar();
ReflectionUtil::setId($calendar, 1);
$this->assertEquals($calendar, $result->getTargetCalendar());
$this->assertEquals('testCalendarAlias', $result->getCalendarAlias());
$this->assertEquals(2, $result->getCalendar());
$this->assertEquals(100, $result->getPosition());
$this->assertTrue($result->getVisible());
$this->assertEquals('#00FF00', $result->getBackgroundColor());
$view = $form->createView();
$children = $view->children;
foreach (array_keys($formData) as $key) {
$this->assertArrayHasKey($key, $children);
}
}
/**
* @inheritDoc
*/
protected function getExtensions()
{
$this->registry = $this->createMock(ManagerRegistry::class);
$em = $this->createMock(EntityManager::class);
$meta = $this->createMock(ClassMetadata::class);
$repo = $this->createMock(EntityRepository::class);
$calendar = new Calendar();
ReflectionUtil::setId($calendar, 1);
$this->registry->expects($this->any())
->method('getManagerForClass')
->with('OroCalendarBundle:Calendar')
->willReturn($em);
$em->expects($this->any())
->method('getClassMetadata')
->with('OroCalendarBundle:Calendar')
->willReturn($meta);
$em->expects($this->any())
->method('getRepository')
->with('OroCalendarBundle:Calendar')
->willReturn($repo);
$meta->expects($this->any())
->method('getSingleIdentifierFieldName')
->willReturn('id');
$repo->expects($this->any())
->method('find')
->with($calendar->getId())
->willReturn($calendar);
return [
new PreloadedExtension(
$this->loadTypes(),
[]
),
];
}
public function testProcessWithContexts()
{
$context = new User();
ReflectionUtil::setId($context, 123);
$owner = new User();
ReflectionUtil::setId($owner, 321);
$this->request->setMethod('POST');
$defaultCalendar = $this->createMock(Calendar::class);
$this->entity->setCalendar($defaultCalendar);
$this->form->expects($this->any())
->method('get')
->willReturn($this->form);
$this->form->expects($this->once())
->method('has')
->with('contexts')
->willReturn(true);
$this->form->expects($this->once())
->method('isValid')
->willReturn(true);
$defaultCalendar->expects($this->once())
->method('getOwner')
->willReturn($owner);
$this->form->expects($this->any())
->method('getData')
->willReturn([$context]);
$this->activityManager->expects($this->once())
->method('setActivityTargets')
->with(
$this->identicalTo($this->entity),
$this->identicalTo([$context, $owner])
);
$this->activityManager->expects($this->never())
->method('removeActivityTarget');
$this->handler->process($this->entity);
$this->assertSame($defaultCalendar, $this->entity->getCalendar());
}
/**
* @dataProvider supportedMethods
*/
public function testProcessValidDataWithTargetEntityActivity(string $method): void
{
$targetEntity = new User();
ReflectionUtil::setId($targetEntity, 123);
$organization = new Organization();
ReflectionUtil::setId($organization, 1);
$targetEntity->setOrganization($organization);
$defaultCalendar = $this->createMock(Calendar::class);
$this->entity->setCalendar($defaultCalendar);
$this->entityRoutingHelper->expects(self::once())
->method('getEntityClassName')
->willReturn(get_class($targetEntity));
$this->entityRoutingHelper->expects(self::once())
->method('getEntityId')
->willReturn($targetEntity->getId());
$this->entityRoutingHelper->expects(self::once())
->method('getAction')
->willReturn('activity');
$this->request->initialize([], self::FORM_DATA);
$this->request->setMethod($method);
$this->form->expects(self::once())
->method('setData')
->with(self::identicalTo($this->entity));
$this->form->expects(self::once())
->method('submit')
->with(self::identicalTo(self::FORM_DATA));
$this->form->expects(self::once())
->method('isValid')
->willReturn(true);
$this->entityRoutingHelper->expects(self::once())
->method('getEntityReference')
->with(get_class($targetEntity), $targetEntity->getId())
->willReturn($targetEntity);
$this->activityManager->expects(self::once())
->method('addActivityTarget')
->with(self::identicalTo($this->entity), self::identicalTo($targetEntity));
$this->form->expects(self::any())
->method('has')
->willReturn(false);
$this->calendarEventManager->expects(self::once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, true);
$this->objectManager->expects(self::once())
->method('persist')
->with(self::identicalTo($this->entity));
$this->objectManager->expects(self::once())
->method('flush');
self::assertTrue($this->handler->process($this->entity));
self::assertSame($defaultCalendar, $this->entity->getCalendar());
}
/**
* @dataProvider supportedMethods
*/
public function testProcessValidDataWithTargetEntityAssign(string $method): void
{
$targetEntity = new User();
ReflectionUtil::setId($targetEntity, 123);
$organization = new Organization();
ReflectionUtil::setId($organization, 1);
$targetEntity->setOrganization($organization);
$defaultCalendar = $this->createMock(Calendar::class);
$this->entity->setCalendar($defaultCalendar);
$this->entityRoutingHelper->expects(self::once())
->method('getEntityClassName')
->willReturn(get_class($targetEntity));
$this->entityRoutingHelper->expects(self::once())
->method('getEntityId')
->willReturn($targetEntity->getId());
$this->entityRoutingHelper->expects(self::once())
->method('getAction')
->willReturn('assign');
$this->request->initialize([], self::FORM_DATA);
$this->request->setMethod($method);
$this->form->expects(self::once())
->method('setData')
->with(self::identicalTo($this->entity));
$this->form->expects(self::once())
->method('submit')
->with(self::identicalTo(self::FORM_DATA));
$this->form->expects(self::once())
->method('isValid')
->willReturn(true);
$this->entityRoutingHelper->expects(self::once())
->method('getEntityReference')
->with(get_class($targetEntity), $targetEntity->getId())
->willReturn($targetEntity);
$this->activityManager->expects(self::never())
->method('addActivityTarget')
->with(self::identicalTo($this->entity), self::identicalTo($targetEntity));
$this->tokenAccessor->expects(self::once())
->method('getUserId')
->willReturn(100);
$repository = $this->createMock(CalendarRepository::class);
$calendar = $this->createMock(Calendar::class);
$repository->expects(self::once())
->method('findDefaultCalendar')
->willReturn($calendar);
$this->objectManager->expects(self::once())
->method('getRepository')
->willReturn($repository);
$this->form->expects(self::any())
->method('has')
->willReturn(false);
$this->calendarEventManager->expects(self::once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, true);
$this->objectManager->expects(self::once())
->method('persist')
->with(self::identicalTo($this->entity));
$this->objectManager->expects(self::once())
->method('flush');
self::assertTrue($this->handler->process($this->entity));
self::assertNotSame($defaultCalendar, $this->entity->getCalendar());
}
/**
* @dataProvider supportedMethods
*/
public function testProcessWithContexts(string $method): void
{
$context = new User();
ReflectionUtil::setId($context, 123);
$owner = new User();
ReflectionUtil::setId($owner, 321);
$organization = new Organization();
ReflectionUtil::setId($organization, 1);
$owner->setOrganization($organization);
$this->request->initialize([], self::FORM_DATA);
$this->request->setMethod($method);
$this->form->expects(self::any())
->method('get')
->willReturnCallback(fn ($p) => 'notifyAttendees' === $p ? $this->notifyAttendeesForm : $this->form);
$defaultCalendar = $this->createMock(Calendar::class);
$this->entity->setCalendar($defaultCalendar);
$this->form->expects(self::once())
->method('isValid')
->willReturn(true);
$this->form->expects(self::any())
->method('has')
->withConsecutive(
['contexts'],
['notifyAttendees']
)
->willReturn(true);
$defaultCalendar->expects(self::once())
->method('getOwner')
->willReturn($owner);
$this->form->expects(self::any())
->method('getData')
->willReturn([$context]);
$this->activityManager->expects(self::once())
->method('setActivityTargets')
->with(
self::identicalTo($this->entity),
self::identicalTo([$context, $owner])
);
$this->activityManager->expects(self::never())
->method('removeActivityTarget');
self::assertTrue($this->handler->process($this->entity));
self::assertSame($defaultCalendar, $this->entity->getCalendar());
}
public function testProcessPutWithNotifyAttendeesNotPassedWorks()
{
ReflectionUtil::setId($this->entity, 123);
$this->request->setMethod('PUT');
$this->setExpectedFormValues([]);
$this->calendarEventManager->expects($this->once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, false);
$this->notificationManager->expects($this->once())
->method('onUpdate')
->with($this->entity, clone $this->entity, NotificationManager::NONE_NOTIFICATIONS_STRATEGY);
$this->featureChecker->expects(self::once())
->method('isFeatureEnabled')
->with('calendar_events_attendee_notifications')
->willReturn(true);
$this->handler->process($this->entity);
}
public function testProcessPutWithNotifyAttendeesNoneWorks()
{
ReflectionUtil::setId($this->entity, 123);
$this->request->setMethod('PUT');
$this->setExpectedFormValues([
'notifyAttendees' => NotificationManager::NONE_NOTIFICATIONS_STRATEGY,
]);
$this->calendarEventManager->expects($this->once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, false);
$this->notificationManager->expects($this->once())
->method('onUpdate')
->with($this->entity, clone $this->entity, NotificationManager::NONE_NOTIFICATIONS_STRATEGY);
$this->featureChecker->expects(self::once())
->method('isFeatureEnabled')
->with('calendar_events_attendee_notifications')
->willReturn(true);
$this->handler->process($this->entity);
}
public function testProcessPutWithNotifyAttendeesAddedOrDeletedWorks()
{
$this->request->setMethod('PUT');
ReflectionUtil::setId($this->entity, 123);
$this->entity->addAttendee(new Attendee());
$this->setExpectedFormValues(
[
'notifyAttendees' => NotificationManager::ADDED_OR_DELETED_NOTIFICATIONS_STRATEGY,
]
);
$this->calendarEventManager->expects($this->once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, false);
$this->notificationManager->expects($this->once())
->method('onUpdate')
->with($this->entity, clone $this->entity, NotificationManager::ADDED_OR_DELETED_NOTIFICATIONS_STRATEGY);
$this->featureChecker->expects(self::once())
->method('isFeatureEnabled')
->with('calendar_events_attendee_notifications')
->willReturn(true);
$this->handler->process($this->entity);
}
public function testProcessPutWithNotifyAttendeesAllWorksAndDisabledInvitations()
{
$this->request->setMethod('PUT');
ReflectionUtil::setId($this->entity, 123);
$this->entity->addAttendee(new Attendee());
$this->setExpectedFormValues(['notifyAttendees' => NotificationManager::ALL_NOTIFICATIONS_STRATEGY]);
$this->calendarEventManager->expects($this->once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, false);
$this->notificationManager->expects($this->never())
->method('onUpdate');
$this->featureChecker->expects(self::once())
->method('isFeatureEnabled')
->with('calendar_events_attendee_notifications')
->willReturn(false);
$this->handler->process($this->entity);
}
public function testProcessPutWithNotifyAttendeesAllWorks()
{
$this->request->setMethod('PUT');
ReflectionUtil::setId($this->entity, 123);
$this->entity->addAttendee(new Attendee());
$this->setExpectedFormValues(['notifyAttendees' => NotificationManager::ALL_NOTIFICATIONS_STRATEGY]);
$this->calendarEventManager->expects($this->once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, false);
$this->notificationManager->expects($this->once())
->method('onUpdate')
->with($this->entity, clone $this->entity, NotificationManager::ALL_NOTIFICATIONS_STRATEGY);
$this->featureChecker->expects(self::once())
->method('isFeatureEnabled')
->with('calendar_events_attendee_notifications')
->willReturn(true);
$this->handler->process($this->entity);
}
public function testProcessWithContexts()
{
$context = new User();
ReflectionUtil::setId($context, 123);
$owner = new User();
ReflectionUtil::setId($owner, 321);
$this->request->setMethod('POST');
$defaultCalendar = $this->createMock(Calendar::class);
$this->entity->setCalendar($defaultCalendar);
$defaultCalendar->expects($this->once())
->method('getOwner')
->willReturn($owner);
$this->setExpectedFormValues(['contexts' => [$context]]);
$this->activityManager->expects($this->once())
->method('setActivityTargets')
->with(
$this->entity,
[$context, $owner]
);
$this->activityManager->expects($this->never())
->method('removeActivityTarget');
$this->calendarEventManager->expects($this->once())
->method('onEventUpdate')
->with($this->entity, clone $this->entity, $this->organization, false);
$this->handler->process($this->entity);
$this->assertSame($defaultCalendar, $this->entity->getCalendar());
}
/**
* Test existing user modification
*/
public function testOnFlushUpdateUser()
{
$user = new User();
ReflectionUtil::setId($user, 123);
$org = new Organization();
ReflectionUtil::setId($org, 1);
$coll = $this->getPersistentCollection($user, ['fieldName' => 'organizations'], [$org]);
$newCalendar = new Calendar();
$newCalendar->setOwner($user);
$newCalendar->setOrganization($org);
$calendarMetadata = new ClassMetadata(get_class($newCalendar));
$calendarRepo = $this->createMock(CalendarRepository::class);
$calendarRepo->expects($this->any())
->method('findDefaultCalendar')
->willReturn(false);
$this->uow->expects($this->once())
->method('getScheduledEntityInsertions')
->willReturn([]);
$this->uow->expects($this->once())
->method('getScheduledCollectionUpdates')
->willReturn([$coll]);
$this->em->expects($this->once())
->method('getRepository')
->with('OroCalendarBundle:Calendar')
->willReturn($calendarRepo);
$this->em->expects($this->once())
->method('persist')
->with($this->equalTo($newCalendar));
$this->em->expects($this->once())
->method('getClassMetadata')
->with(Calendar::class)
->willReturn($calendarMetadata);
$this->uow->expects($this->once())
->method('computeChangeSet')
->with($calendarMetadata, $newCalendar);
$this->listener->onFlush(new OnFlushEventArgs($this->em));
}
/**
* Test new user creation
*/
public function testOnFlushCreateUser()
{
$user = new User();
$org1 = new Organization();
ReflectionUtil::setId($org1, 1);
$org2 = new Organization();
ReflectionUtil::setId($org2, 2);
$user->setOrganization($org1);
$user->addOrganization($org1);
$user->addOrganization($org2);
$newCalendar1 = new Calendar();
$newCalendar1->setOwner($user)->setOrganization($org1);
$newCalendar2 = new Calendar();
$newCalendar2->setOwner($user)->setOrganization($org2);
$calendarMetadata = new ClassMetadata(get_class($newCalendar1));
$this->uow->expects($this->once())
->method('getScheduledEntityInsertions')
->willReturn([$user]);
$this->uow->expects($this->once())
->method('getScheduledCollectionUpdates')
->willReturn([]);
$this->em->expects($this->once())
->method('getClassMetadata')
->with(Calendar::class)
->willReturn($calendarMetadata);
$this->em->expects($this->exactly(2))
->method('persist')
->withConsecutive(
[$this->equalTo($newCalendar1)],
[$this->equalTo($newCalendar2)]
);
$this->uow->expects($this->exactly(2))
->method('computeChangeSet')
->withConsecutive(
[$this->identicalTo($calendarMetadata), $this->equalTo($newCalendar1)],
[$this->identicalTo($calendarMetadata), $this->equalTo($newCalendar2)]
);
$this->listener->onFlush(new OnFlushEventArgs($this->em));
}
private function getSystemCalendar(int $id): SystemCalendar
{
$systemCalendar = new SystemCalendar();
ReflectionUtil::setId($systemCalendar, $id);
return $systemCalendar;
}
public function testIdGetter()
{
$obj = new SystemCalendar();
ReflectionUtil::setId($obj, 1);
$this->assertEquals(1, $obj->getId());
}
public function testIdGetter()
{
$obj = new Calendar();
ReflectionUtil::setId($obj, 1);
$this->assertEquals(1, $obj->getId());
}
public function testToString()
{
$entity = new CalendarProperty();
self::assertSame('', (string) $entity);
ReflectionUtil::setId($entity, 1);
self::assertSame('1', (string) $entity);
}
public function testGetCalendarUidPublicCalendar()
{
$calendar = new SystemCalendar();
ReflectionUtil::setId($calendar, 123);
$calendar->setPublic(true);
$obj = new CalendarEvent();
$obj->setSystemCalendar($calendar);
$this->assertEquals('public_123', $obj->getCalendarUid());
}
public function testGetCalendarUidSystemCalendar()
{
$calendar = new SystemCalendar();
ReflectionUtil::setId($calendar, 123);
$obj = new CalendarEvent();
$obj->setSystemCalendar($calendar);
$this->assertEquals('system_123', $obj->getCalendarUid());
}
public function testGetCalendarUidUserCalendar()
{
$calendar = new Calendar();
ReflectionUtil::setId($calendar, 123);
$obj = new CalendarEvent();
$obj->setCalendar($calendar);
$this->assertEquals('user_123', $obj->getCalendarUid());
}
public function testGetReminderDataWithLogicException()
{
$this->expectException(\LogicException::class);
$this->expectExceptionMessage("Only user's calendar events can have reminders. Event Id: 1.");
$obj = new CalendarEvent();
ReflectionUtil::setId($obj, 1);
$obj->getReminderData();
}
public function testGetReminderData()
{
$obj = new CalendarEvent();
ReflectionUtil::setId($obj, 1);
$obj->setTitle('testTitle');
$calendar = new Calendar();
$calendar->setOwner(new User());
$obj->setCalendar($calendar);
/** @var ReminderData $reminderData */
$reminderData = $obj->getReminderData();
$this->assertEquals($reminderData->getSubject(), $obj->getTitle());
$this->assertEquals($reminderData->getExpireAt(), $obj->getStart());
$this->assertSame($reminderData->getRecipient(), $calendar->getOwner());
}
public function testIdGetter()
{
$obj = new CalendarEvent();
ReflectionUtil::setId($obj, 1);
$this->assertEquals(1, $obj->getId());
}
public function testConvertItem()
{
$user = new User();
ReflectionUtil::setId($user, 1);
$user->setFirstName('testFirstName');
$user->setLastName('testLastName');
$calendar = new Calendar();
ReflectionUtil::setId($calendar, 2);
$calendar->setOwner($user);
$result = $this->handler->convertItem($calendar);
$this->assertEquals($result['id'], $calendar->getId());
$this->assertEquals($result['userId'], $calendar->getOwner()->getId());
}
private function getLocalization(int $id): Localization
{
$localization = new Localization();
ReflectionUtil::setId($localization, $id);
return $localization;
}
private function getWebsite(int $id): Website
{
$website = new Website();
ReflectionUtil::setId($website, $id);
return $website;
}
private function getWebsite(int $id, string $name): Website
{
$website = new Website();
ReflectionUtil::setId($website, $id);
$website->setName($name);
return $website;
}
public function testOnClear()
{
ReflectionUtil::setPropertyValue($this->manager, 'currentWebsite', new Website());
$this->manager->onClear();
self::assertEmpty(ReflectionUtil::getPropertyValue($this->manager, 'currentWebsite'));
}
private function getBackendSessionOptions(): ?array
{
return ReflectionUtil::getPropertyValue($this->kernelDecorator, 'backendSessionOptions');
}
private function createCustomer(int $id): Customer
{
$customer = new Customer();
ReflectionUtil::setId($customer, $id);
return $customer;
}
private function createUser(int $id): CustomerUser
{
$user = new CustomerUser();
ReflectionUtil::setId($user, $id);
return $user;
}
protected function setUp(): void
{
$this->doctrine = $this->createMock(ManagerRegistry::class);
$this->ownershipMetadataProvider = $this->createMock(OwnershipMetadataProviderInterface::class);
$this->authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$this->tokenAccessor = $this->createMock(TokenAccessorInterface::class);
$this->ownerTree = $this->createMock(OwnerTreeInterface::class);
$this->ownerTreeProvider = $this->createMock(OwnerTreeProviderInterface::class);
$this->aclVoter = $this->createMock(AclVoter::class);
$this->aclGroupProvider = $this->createMock(AclGroupProviderInterface::class);
$this->testEntity = new Entity();
$this->currentOrg = new Organization();
$this->currentOrg->setId(1);
$this->currentUser = new CustomerUser();
ReflectionUtil::setId($this->currentUser, 10);
$this->tokenAccessor->expects(self::any())
->method('getUser')
->willReturn($this->currentUser);
$this->tokenAccessor->expects(self::any())
->method('getUserId')
->willReturn($this->currentUser->getId());
$this->tokenAccessor->expects(self::any())
->method('getOrganization')
->willReturn($this->currentOrg);
$this->ownerTreeProvider->expects(self::any())
->method('getTree')
->willReturn($this->ownerTree);
parent::setUp();
}
public function testHandleWithRememberedToken(): void
{
$rememberedToken = new AnonymousCustomerUserToken('User');
ReflectionUtil::setPropertyValue($this->listener, 'rememberedToken', $rememberedToken);
$this->tokenStorage->expects(self::once())
->method('getToken')
->willReturn(null);
$this->tokenStorage->expects(self::once())
->method('setToken')
->with($rememberedToken);
($this->listener)($this->getRequestEvent(new Request()));
self::assertNull(ReflectionUtil::getPropertyValue($this->listener, 'rememberedToken'));
self::assertEmpty($this->logger->cleanLogs());
}
private function getCustomerVisitor(int $id, string $sessionId): CustomerVisitor
{
$visitor = new CustomerVisitor();
ReflectionUtil::setId($visitor, $id);
$visitor->setSessionId($sessionId);
return $visitor;
}
private function getCustomerUserWithData(): CustomerUser
{
$user = new CustomerUser();
ReflectionUtil::setId($user, 123);
$user->setEnabled(true);
$user->setConfirmed(true);
$user->setEmail('[email protected]');
$user->setFirstName('John');
$user->setLastName('Doe');
$user->setLastLogin(new \DateTime('01-01-2010'));
$user->setCreatedAt(new \DateTime('01-01-2000'));
return $user;
}
private function getCustomerUser(int $id, Organization $organization, Customer $customer = null): CustomerUser
{
$customerUser = new CustomerUser();
ReflectionUtil::setId($customerUser, $id);
$customerUser->setOrganization($organization);
if (null !== $customer) {
$customerUser->setCustomer($customer);
}
return $customerUser;
}
private function getCustomer(int $id, Customer $parent = null): Customer
{
$customer = new Customer();
ReflectionUtil::setId($customer, $id);
if (null !== $parent) {
$customer->setParent($parent);
}
return $customer;
}
public function buildViewDataProvider(): array
{
$customerId = 42;
$customer = new Customer();
ReflectionUtil::setId($customer, $customerId);
return [
'without customer' => [
'parentData' => null,
'expectedParentId' => null,
],
'with customer' => [
'parentData' => $customer,
'expectedParentId' => $customerId,
],
];
}
/**
* @dataProvider onSubmitDataProvider
*/
public function testOnSubmit(?int $customerUserId, Website $website = null, Website $expectedWebsite = null)
{
$this->authorizationChecker->expects($this->any())
->method('isGranted')
->willReturn(false);
$this->websiteManager->expects($this->any())
->method('getCurrentWebsite')
->willReturn($website);
$customer = new Customer();
$newCustomerUser = new CustomerUser();
ReflectionUtil::setId($newCustomerUser, $customerUserId);
$newCustomerUser->setCustomer($customer);
$form = $this->factory->create(FrontendCustomerUserType::class, $newCustomerUser, []);
$form->submit([]);
$this->assertTrue($form->isValid());
$this->assertTrue($form->isSynchronized());
$this->assertEquals($expectedWebsite, $form->getData()->getWebsite());
}
public function submitProvider(): array
{
$newCustomerUser = new CustomerUser();
$customer = new Customer();
$newCustomerUser->setCustomer($customer);
$existingCustomerUser = new CustomerUser();
ReflectionUtil::setId($existingCustomerUser, 42);
$existingCustomerUser->setFirstName('John');
$existingCustomerUser->setLastName('Doe');
$existingCustomerUser->setEmail('[email protected]');
$existingCustomerUser->setPassword('123456');
$existingCustomerUser->setCustomer($customer);
$existingCustomerUser->addAddress($this->getAddresses()[1]);
$alteredExistingCustomerUser = clone $existingCustomerUser;
$alteredExistingCustomerUser->setEnabled(false);
$alteredExistingCustomerUser->setCustomer($customer);
$alteredExistingCustomerUserWithRole = clone $alteredExistingCustomerUser;
$alteredExistingCustomerUserWithRole->setUserRoles([$this->getRole(2, 'test02')]);
$alteredExistingCustomerUserWithAddresses = clone $alteredExistingCustomerUser;
$alteredExistingCustomerUserWithAddresses->addAddress($this->getAddresses()[2]);
return
[
'user without submitted data' => [
'defaultData' => $newCustomerUser,
'submittedData' => [],
'expectedData' => $newCustomerUser,
],
'altered existing user' => [
'defaultData' => $existingCustomerUser,
'submittedData' => [
'firstName' => 'John',
'lastName' => 'Doe',
'email' => '[email protected]',
'customer' => $existingCustomerUser->getCustomer()->getName(),
],
'expectedData' => $alteredExistingCustomerUser,
],
'altered existing user with roles' => [
'defaultData' => $existingCustomerUser,
'submittedData' => [
'firstName' => 'John',
'lastName' => 'Doe',
'email' => '[email protected]',
'customer' => $existingCustomerUser->getCustomer()->getName(),
'userRoles' => [2],
],
'expectedData' => $alteredExistingCustomerUserWithRole,
'altered existing user with addresses' => [
'defaultData' => $existingCustomerUser,
'submittedData' => [
'firstName' => 'John',
'lastName' => 'Doe',
'email' => '[email protected]',
'customer' => $alteredExistingCustomerUserWithRole->getCustomer()->getName(),
'addresses' => [1, 2],
],
'expectedData' => $alteredExistingCustomerUserWithAddresses,
],
],
];
}
private function prepareFormForEvents(): FormInterface
{
[$customerUser1, $customerUser2, $customerUser3, $customerUser4] = array_values($this->getCustomerUsers());
$role = new CustomerUserRole();
ReflectionUtil::setId($role, 1);
$predefinedRole = new CustomerUserRole();
ReflectionUtil::setId($predefinedRole, 2);
$predefinedRole->addCustomerUser($customerUser1);
$predefinedRole->addCustomerUser($customerUser2);
$predefinedRole->addCustomerUser($customerUser3);
$predefinedRole->addCustomerUser($customerUser4);
return $this->factory->create(
FrontendCustomerUserRoleType::class,
$role,
['privilege_config' => $this->privilegeConfig, 'predefined_role' => $predefinedRole]
);
}
public function testPostSubmit()
{
[$customerUser1, , , $customerUser4] = array_values($this->getCustomerUsers());
[$customer1] = array_values($this->getCustomers());
$form = $this->prepareFormForEvents();
$form->get('appendUsers')->setData([$customerUser1]);
$form->get('removeUsers')->setData([$customerUser4]);
$role = new CustomerUserRole();
ReflectionUtil::setId($role, 1);
$role->setCustomer($customer1);
$event = new FormEvent($form, $role);
$this->formType->postSubmit($event);
$predefinedRole = $form->getConfig()->getOption('predefined_role');
$this->assertTrue($predefinedRole->getCustomerUsers()->contains($customerUser4));
$this->assertFalse($predefinedRole->getCustomerUsers()->contains($customerUser1));
}
public function submitDataProvider(): array
{
$roleLabel = 'customer_role_label';
$alteredRoleLabel = 'altered_role_label';
$customer = new Customer();
$defaultRole = new CustomerUserRole('');
$defaultRole->setLabel($roleLabel);
$defaultRole->setCustomer($customer);
$existingRoleBefore = new CustomerUserRole();
ReflectionUtil::setId($existingRoleBefore, 1);
$existingRoleBefore
->setLabel($roleLabel)
->setRole($roleLabel, false)
->setCustomer($customer);
$existingRoleAfter = new CustomerUserRole();
ReflectionUtil::setId($existingRoleAfter, 1);
$existingRoleAfter
->setLabel($alteredRoleLabel)
->setRole($roleLabel, false)
->setCustomer($customer);
return [
'empty' => [
'options' => ['privilege_config' => $this->privilegeConfig],
'defaultData' => $defaultRole,
'viewData' => $defaultRole,
'submittedData' => [
'label' => $roleLabel,
'customer' => $defaultRole->getCustomer()->getName(),
],
'expectedData' => $defaultRole,
],
'existing' => [
'options' => ['privilege_config' => $this->privilegeConfig],
'defaultData' => $existingRoleBefore,
'viewData' => $existingRoleBefore,
'submittedData' => [
'label' => $alteredRoleLabel,
'customer' => $existingRoleBefore->getCustomer()->getName(),
],
'expectedData' => $existingRoleAfter,
],
];
}
private function getRole(int $id, string $label): CustomerUserRole
{
$role = new CustomerUserRole($label);
ReflectionUtil::setId($role, $id);
$role->setLabel($label);
return $role;
}
public function submitProvider(): array
{
$entity = new CustomerUser();
$customer = new Customer();
$entity->setCustomer($customer);
$existingEntity = new CustomerUser();
ReflectionUtil::setId($existingEntity, 42);
$existingEntity->setFirstName('John');
$existingEntity->setLastName('Doe');
$existingEntity->setEmail('[email protected]');
$existingEntity->setPassword('123456');
$existingEntity->setCustomer($customer);
$updatedEntity = clone $existingEntity;
$updatedEntity->setFirstName('John UP');
$updatedEntity->setLastName('Doe UP');
$updatedEntity->setEmail('[email protected]');
return [
'new user' => [
'defaultData' => $entity,
'submittedData' => [],
'expectedData' => $entity,
],
'updated user' => [
'defaultData' => $existingEntity,
'submittedData' => [
'firstName' => $updatedEntity->getFirstName(),
'lastName' => $updatedEntity->getLastName(),
'email' => $updatedEntity->getEmail(),
'customer' => $updatedEntity->getCustomer()->getName(),
],
'expectedData' => $updatedEntity,
],
];
}
protected function getCustomerUserAddress(int $id): CustomerUserAddress
{
$customerUserAddress = new CustomerUserAddress();
ReflectionUtil::setId($customerUserAddress, $id);
return $customerUserAddress;
}
protected function getUser(int $id): User
{
$user = new User();
ReflectionUtil::setId($user, $id);
return $user;
}
protected function getRole(int $id, string $label): CustomerUserRole
{
$role = new CustomerUserRole($label);
ReflectionUtil::setId($role, $id);
$role->setLabel($label);
return $role;
}
private static function createCustomer(int $id, string $name): Customer
{
$customer = new Customer();
ReflectionUtil::setId($customer, $id);
$customer->setName($name);
return $customer;
}
public function submitProvider(): array
{
$newCustomerUser = new CustomerUser();
$newCustomerUser->setOrganization(new Organization());
$existingCustomerUser = clone $newCustomerUser;
ReflectionUtil::setId($existingCustomerUser, 42);
$existingCustomerUser->setFirstName('Mary');
$existingCustomerUser->setLastName('Doe');
$existingCustomerUser->setEmail('[email protected]');
$existingCustomerUser->setPassword('123456');
$existingCustomerUser->setCustomer($this->getCustomer(1));
$existingCustomerUser->addAddress($this->getAddresses()[1]);
$existingCustomerUser->setOrganization(new Organization());
$existingCustomerUser->addSalesRepresentative($this->getUser(1));
$alteredExistingCustomerUser = clone $existingCustomerUser;
$alteredExistingCustomerUser->setCustomer($this->getCustomer(2));
$alteredExistingCustomerUser->setEnabled(false);
$alteredExistingCustomerUserWithRole = clone $alteredExistingCustomerUser;
$alteredExistingCustomerUserWithRole->setUserRoles([$this->getRole(2, 'test02')]);
$alteredExistingCustomerUserWithAddresses = clone $alteredExistingCustomerUser;
$alteredExistingCustomerUserWithAddresses->addAddress($this->getAddresses()[2]);
$alteredExistingCustomerUserWithSalesRepresentatives = clone $alteredExistingCustomerUser;
$alteredExistingCustomerUserWithSalesRepresentatives->addSalesRepresentative($this->getUser(2));
return
[
'user without submitted data' => [
'defaultData' => $newCustomerUser,
'submittedData' => [],
'expectedData' => $newCustomerUser,
],
'altered existing user' => [
'defaultData' => $existingCustomerUser,
'submittedData' => [
'firstName' => 'Mary',
'lastName' => 'Doe',
'email' => '[email protected]',
'customer' => 2,
],
'expectedData' => $alteredExistingCustomerUser,
],
'altered existing user with roles' => [
'defaultData' => $existingCustomerUser,
'submittedData' => [
'firstName' => 'Mary',
'lastName' => 'Doe',
'email' => '[email protected]',
'customer' => 2,
'userRoles' => [2],
],
'expectedData' => $alteredExistingCustomerUserWithRole,
'rolesGranted' => true,
],
'altered existing user with addresses' => [
'defaultData' => $existingCustomerUser,
'submittedData' => [
'firstName' => 'Mary',
'lastName' => 'Doe',
'email' => '[email protected]',
'customer' => 2,
'addresses' => [1, 2],
],
'expectedData' => $alteredExistingCustomerUserWithAddresses,
],
'altered existing user with salesRepresentatives' => [
'defaultData' => $existingCustomerUser,
'submittedData' => [
'firstName' => 'Mary',
'lastName' => 'Doe',
'email' => '[email protected]',
'customer' => 2,
'salesRepresentatives' => [],
],
'expectedData' => $alteredExistingCustomerUserWithSalesRepresentatives,
],
];
}
private function getCustomerAddress(int $id): CustomerAddress
{
$customerAddress = new CustomerAddress();
ReflectionUtil::setId($customerAddress, $id);
return $customerAddress;
}
private function getCustomerGroup(int $id): CustomerGroup
{
$customerGroup = new CustomerGroup();
ReflectionUtil::setId($customerGroup, $id);
return $customerGroup;
}
private function getUser(int $id): User
{
$user = new User();
ReflectionUtil::setId($user, $id);
return $user;
}
public function submitDataProvider(): array
{
$groupName = 'customer_group_name';
$alteredGroupName = 'altered_group_name';
$defaultGroup = new CustomerGroup();
$defaultGroup->setName($groupName);
$existingGroupBefore = new CustomerGroup();
ReflectionUtil::setId($existingGroupBefore, 1);
$existingGroupBefore->setName($groupName);
$existingGroupAfter = clone $existingGroupBefore;
$existingGroupAfter->setName($alteredGroupName);
return [
'empty' => [
'options' => [],
'defaultData' => null,
'viewData' => null,
'submittedData' => [
'name' => $groupName,
],
'expectedData' => $defaultGroup,
],
'existing' => [
'options' => [],
'defaultData' => $existingGroupBefore,
'viewData' => $existingGroupBefore,
'submittedData' => [
'name' => $alteredGroupName,
],
'expectedData' => $existingGroupAfter,
],
];
}
protected static function createCustomer(int $id, string $name): Customer
{
$customer = new Customer();
ReflectionUtil::setId($customer, $id);
$customer->setName($name);
return $customer;
}
public function submitDataProvider(): array
{
$roleLabel = 'customer_role_label';
$alteredRoleLabel = 'altered_role_label';
$defaultRole = new CustomerUserRole();
$defaultRole->setLabel($roleLabel);
$existingRoleBefore = new CustomerUserRole();
ReflectionUtil::setId($existingRoleBefore, 1);
$existingRoleBefore
->setLabel($roleLabel)
->setRole($roleLabel, false);
$existingRoleAfter = new CustomerUserRole();
ReflectionUtil::setId($existingRoleAfter, 1);
$existingRoleAfter
->setLabel($alteredRoleLabel)
->setRole($roleLabel, false);
return [
'empty' => [
'options' => ['privilege_config' => $this->privilegeConfig],
'defaultData' => null,
'viewData' => null,
'submittedData' => [
'label' => $roleLabel,
],
'expectedData' => $defaultRole,
],
'existing' => [
'options' => ['privilege_config' => $this->privilegeConfig],
'defaultData' => $existingRoleBefore,
'viewData' => $existingRoleBefore,
'submittedData' => [
'label' => $alteredRoleLabel,
],
'expectedData' => $existingRoleAfter,
],
];
}
public function testProcessExistingCustomerUser()
{
$entity = new CustomerUser();
ReflectionUtil::setId($entity, 1);
$this->form->expects($this->once())
->method('setData')
->with($entity);
$this->form->expects($this->once())
->method('submit')
->with([], true);
$this->form->expects($this->once())
->method('isValid')
->willReturn(true);
$this->request->setMethod('POST');
$em = $this->createMock(EntityManager::class);
$this->doctrineHelper->expects($this->once())
->method('getEntityManager')
->with($entity)
->willReturn($em);
$em->expects($this->once())
->method('beginTransaction');
$em->expects($this->once())
->method('commit');
$this->userManager->expects($this->never())
->method('register');
$this->userManager->expects($this->once())
->method('updateUser')
->with($entity);
$this->userManager->expects($this->once())
->method('reloadUser')
->with($entity);
$this->assertProcessAfterEventsTriggered($this->form, $entity);
$this->assertTrue($this->handler->process($entity, $this->form, $this->request));
}
private function getCustomerUser(int $id): CustomerUser
{
$customerUser = new CustomerUser();
ReflectionUtil::setId($customerUser, $id);
return $customerUser;
}
protected function createCustomerUserRole(string $role, int $id = null): CustomerUserRole
{
$entity = new CustomerUserRole($role);
ReflectionUtil::setId($entity, $id);
return $entity;
}
public function getWebsite(int $id): Website
{
$website = new Website();
ReflectionUtil::setId($website, $id);
return $website;
}
public function testId()
{
$entity = new CustomerUserApi();
self::assertNull($entity->getId());
$id = 1;
ReflectionUtil::setId($entity, $id);
self::assertEquals($id, $entity->getId());
}
private function getCustomer(int $id): Customer
{
$customer = new Customer();
ReflectionUtil::setId($customer, $id);
return $customer;
}
private function getCustomerUser(int $id, int $customerId = null): CustomerUser
{
$user = new CustomerUser();
ReflectionUtil::setId($user, $id);
if ($customerId) {
$user->setCustomer($this->getCustomer($customerId));
}
return $user;
}
private function getCustomer(int $id = null): Customer
{
$entity = new Customer();
ReflectionUtil::setId($entity, $id);
return $entity;
}
private function getGroup(int $id): CustomerGroup
{
$group = new CustomerGroup();
ReflectionUtil::setId($group, $id);
return $group;
}
public function testWithNotFoundParentLastAttempt()
{
$context = new Context([
'attempts' => 3,
'max_attempts' => 3,
]);
$data = ['name' => 'customer', 'parent' => '0'];
$context->setValue('itemData', $data);
$context->setValue('rawItemData', $data);
$this->strategy->setImportExportContext($context);
$parent = new Customer();
ReflectionUtil::setId($parent, 0);
$customer = $this->createCustomer($this->getReference('user_with_main_organization_access'), $parent);
$processedCustomer = $this->strategy->process($customer);
$this->assertNull($processedCustomer);
$this->assertEquals(['Error in row #0. Parent customer with ID "0" was not found'], $context->getErrors());
$this->assertEmpty($context->getPostponedRows());
}
public function testWithNotFoundParentNotLastAttempt()
{
$context = new Context([
'attempts' => 2,
'max_attempts' => 3,
]);
$data = ['name' => 'customer', 'parent' => '0'];
$context->setValue('itemData', $data);
$context->setValue('rawItemData', $data);
$this->strategy->setImportExportContext($context);
$parent = new Customer();
ReflectionUtil::setId($parent, 0);
$customer = $this->createCustomer($this->getReference('user_with_main_organization_access'), $parent);
$processedCustomer = $this->strategy->process($customer);
$this->assertNull($processedCustomer);
$this->assertEmpty($context->getErrors());
$this->assertEquals([$data], $context->getPostponedRows());
}