diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index f2421066e..000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,55 +0,0 @@ -version: 2 - -jobs: - build: - environment: - DATABASE_URL: mysql://root@127.0.0.1:3306/su_articles_test?serverVersion=5.7 - ARTICLE_TEST_CASE: extend - docker: - - image: circleci/php:8.1-node-browsers - - image: circleci/mysql:5.7 - environment: - MYSQL_ALLOW_EMPTY_PASSWORD: true - - image: elasticsearch:7.5.2 - environment: - - cluster.name: es-test-cluster - - xpack.security.enabled: false - - transport.host: localhost - - network.host: 127.0.0.1 - - http.port: 9200 - - discovery.type: single-node - steps: - - checkout - - run: - name: Install OS dependencies (mysql, gd) - command: | - sudo apt-get install -y libpng-dev - sudo docker-php-ext-install pdo_mysql gd - parallel: true - - run: echo -e "memory_limit=2G" | sudo tee /usr/local/etc/php/php.ini > /dev/null - - run: /usr/local/bin/composer remove php-cs-fixer/shim --dev --no-update - - run: /usr/local/bin/composer require "elasticsearch/elasticsearch:~7.5.2" --no-update - - restore_cache: - keys: - - composer-v2-{{ checksum "composer.json" }} - - composer-v2- - - run: php -d memory_limit=-1 /usr/local/bin/composer install -n --prefer-dist - - save_cache: - key: composer-v2-{{ checksum "composer.json" }} - paths: - - vendor - - ~/.composer/cache - - run: - name: Test Elasticsearch - command: | - sleep 10 && wget --waitretry=10 --retry-connrefused -v http://127.0.0.1:9200/ - cat index.html - - run: - name: Command Create Test Database - command: | - composer bootstrap-test-env - - run: - name: List Bundles - command: - ./Tests/Application/bin/adminconsole debug:config - - run: composer test diff --git a/Admin/ArticleAdmin.php b/Admin/ArticleAdmin.php deleted file mode 100644 index 0b6aefa69..000000000 --- a/Admin/ArticleAdmin.php +++ /dev/null @@ -1,502 +0,0 @@ -viewBuilderFactory = $viewBuilderFactory; - $this->securityChecker = $securityChecker; - $this->localizationManager = $localizationManager; - $this->structureManager = $structureManager; - $this->kernelBundles = $kernelBundles; - $this->articleTypeConfigurations = $articleTypeConfigurations; - $this->versioningEnabled = $versioningEnabled; - $this->automationViewBuilderFactory = $automationViewBuilderFactory; - } - - public function configureNavigationItems(NavigationItemCollection $navigationItemCollection): void - { - if (!$this->securityChecker->hasPermission(static::SECURITY_CONTEXT, PermissionTypes::EDIT)) { - return; - } - - $hasArticleTypeWithEditPermissions = false; - foreach ($this->getTypes() as $typeKey => $typeConfig) { - if (!$this->securityChecker->hasPermission(static::getArticleSecurityContext($typeKey), PermissionTypes::EDIT)) { - continue; - } - - $hasArticleTypeWithEditPermissions = true; - break; - } - - if (!$hasArticleTypeWithEditPermissions) { - return; - } - - $articleItem = new NavigationItem('sulu_article.articles'); - $articleItem->setPosition(20); - $articleItem->setIcon('su-newspaper'); - $articleItem->setView(static::LIST_VIEW); - - $navigationItemCollection->add($articleItem); - } - - public function configureViews(ViewCollection $viewCollection): void - { - if (!$this->securityChecker->hasPermission(static::SECURITY_CONTEXT, PermissionTypes::EDIT)) { - return; - } - - $locales = \array_values( - \array_map( - function(Localization $localization) { - return $localization->getLocale(); - }, - $this->localizationManager->getLocalizations() - ) - ); - - $viewCollection->add( - $this->viewBuilderFactory->createTabViewBuilder(static::LIST_VIEW, '/articles') - ->addRouterAttributesToBlacklist(['active', 'filter', 'limit', 'page', 'search', 'sortColumn', 'sortOrder']) - ); - - foreach ($this->getTypes() as $typeKey => $typeConfig) { - if (!$this->securityChecker->hasPermission(static::getArticleSecurityContext($typeKey), PermissionTypes::EDIT)) { - continue; - } - - $formToolbarActionsWithoutType = []; - $formToolbarActionsWithType = []; - $listToolbarActions = []; - - if ($this->securityChecker->hasPermission(static::SECURITY_CONTEXT, PermissionTypes::ADD) - && $this->securityChecker->hasPermission(static::getArticleSecurityContext($typeKey), PermissionTypes::ADD)) { - $listToolbarActions[] = new ToolbarAction('sulu_admin.add'); - } - - if ($this->securityChecker->hasPermission(static::SECURITY_CONTEXT, PermissionTypes::LIVE) - && $this->securityChecker->hasPermission(static::getArticleSecurityContext($typeKey), PermissionTypes::LIVE)) { - $formToolbarActionsWithoutType[] = new ToolbarAction('sulu_admin.save_with_publishing'); - $formToolbarActionsWithType[] = new ToolbarAction('sulu_admin.save_with_publishing'); - } else { - $formToolbarActionsWithoutType[] = new ToolbarAction('sulu_admin.save'); - $formToolbarActionsWithType[] = new ToolbarAction('sulu_admin.save'); - } - - $formToolbarActionsWithType[] = new ToolbarAction('sulu_admin.type'); - - if ($this->securityChecker->hasPermission(static::SECURITY_CONTEXT, PermissionTypes::DELETE) - && $this->securityChecker->hasPermission(static::getArticleSecurityContext($typeKey), PermissionTypes::DELETE)) { - $formToolbarActionsWithType[] = new DropdownToolbarAction( - 'sulu_admin.delete', - 'su-trash-alt', - [ - new ToolbarAction( - 'sulu_admin.delete', - [ - 'visible_condition' => '(!_permissions || _permissions.delete) && url != "/"', - 'router_attributes_to_back_view' => ['webspace'], - ] - ), - new ToolbarAction( - 'sulu_admin.delete', - [ - 'visible_condition' => '(!_permissions || _permissions.delete) && url != "/"', - 'router_attributes_to_back_view' => ['webspace'], - 'delete_locale' => true, - ] - ), - ] - ); - - $listToolbarActions[] = new ToolbarAction('sulu_admin.delete'); - } - - if ($this->securityChecker->hasPermission(static::SECURITY_CONTEXT, PermissionTypes::LIVE) - && $this->securityChecker->hasPermission(static::getArticleSecurityContext($typeKey), PermissionTypes::LIVE)) { - $editDropdownToolbarActions = [ - new ToolbarAction('sulu_admin.delete_draft'), - new ToolbarAction('sulu_admin.set_unpublished'), - new ToolbarAction('sulu_admin.copy'), - ]; - - if (\count($locales) > 1) { - $editDropdownToolbarActions[] = new ToolbarAction('sulu_admin.copy_locale'); - } - - $formToolbarActionsWithType[] = new DropdownToolbarAction( - 'sulu_admin.edit', - 'su-pen', - $editDropdownToolbarActions - ); - } - - if ($this->securityChecker->hasPermission(static::SECURITY_CONTEXT, PermissionTypes::VIEW) - && $this->securityChecker->hasPermission(static::getArticleSecurityContext($typeKey), PermissionTypes::VIEW)) { - $listToolbarActions[] = new ToolbarAction('sulu_admin.export'); - } - - $metadataRequestParameters = [ - 'tags[sulu_article.type]' => false, - ]; - - if ($typeConfig['type']) { - $metadataRequestParameters = [ - 'tags[sulu_article.type][type]' => $typeConfig['type'], - ]; - } - - $previewCondition = '(__routeAttributes.locale in availableLocales) or !__routeAttributes'; - $viewCollection->add( - $this->viewBuilderFactory->createListViewBuilder(static::LIST_VIEW . '_' . $typeKey, '/:locale/' . $typeKey) - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->setListKey(ArticleDocument::LIST_KEY) - ->setTabTitle($typeConfig['title']) - ->addListAdapters(['table']) - ->addLocales($locales) - ->addRequestParameters(['types' => $typeKey]) - ->setDefaultLocale($locales[0]) - ->setAddView(static::ADD_FORM_VIEW . '_' . $typeKey) - ->setEditView(static::EDIT_FORM_VIEW . '_' . $typeKey) - ->addToolbarActions($listToolbarActions) - ->setParent(static::LIST_VIEW) - ); - - $viewCollection->add( - $this->viewBuilderFactory->createResourceTabViewBuilder(static::ADD_FORM_VIEW . '_' . $typeKey, '/articles/:locale/' . $typeKey . '/add') - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->addLocales($locales) - ->setBackView(static::LIST_VIEW . '_' . $typeKey) - ); - $viewCollection->add( - $this->viewBuilderFactory->createFormViewBuilder(self::ADD_FORM_VIEW_DETAILS . '_' . $typeKey, '/details') - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->addMetadataRequestParameters($metadataRequestParameters) - ->setFormKey('article') - ->setTabTitle('sulu_admin.details') - ->setEditView(static::EDIT_FORM_VIEW . '_' . $typeKey) - ->addToolbarActions($formToolbarActionsWithType) - ->setParent(static::ADD_FORM_VIEW . '_' . $typeKey) - ); - $viewCollection->add( - $this->viewBuilderFactory->createResourceTabViewBuilder(static::EDIT_FORM_VIEW . '_' . $typeKey, '/articles/:locale/' . $typeKey . '/:id') - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->addLocales($locales) - ->setTitleProperty('title') - ->setBackView(static::LIST_VIEW . '_' . $typeKey) - ->addRouterAttributesToBlacklist(['active', 'filter', 'limit', 'page', 'search', 'sortColumn', 'sortOrder']) - ); - $viewCollection->add( - $this->viewBuilderFactory->createPreviewFormViewBuilder(static::EDIT_FORM_VIEW_DETAILS . '_' . $typeKey, '/details') - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->addMetadataRequestParameters($metadataRequestParameters) - ->setFormKey('article') - ->setTabTitle('sulu_admin.details') - ->setTabCondition('shadowOn == false') - ->setTabPriority(1024) - ->addToolbarActions($formToolbarActionsWithType) - ->setPreviewCondition($previewCondition) - ->setParent(static::EDIT_FORM_VIEW . '_' . $typeKey) - ); - $viewCollection->add( - $this->viewBuilderFactory->createPreviewFormViewBuilder(static::EDIT_FORM_VIEW_SEO . '_' . $typeKey, '/seo') - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->setFormKey('page_seo') - ->setTabTitle('sulu_page.seo') - ->setTabCondition('shadowOn == false') - ->addToolbarActions($formToolbarActionsWithoutType) - ->setTitleVisible(true) - ->setPreviewCondition($previewCondition) - ->setParent(static::EDIT_FORM_VIEW . '_' . $typeKey) - ); - $viewCollection->add( - $this->viewBuilderFactory->createPreviewFormViewBuilder(static::EDIT_FORM_VIEW_EXCERPT . '_' . $typeKey, '/excerpt') - ->setResourceKey('articles') - ->setFormKey('page_excerpt') - ->setTabTitle('sulu_page.excerpt') - ->setTabCondition('shadowOn == false') - ->addToolbarActions($formToolbarActionsWithoutType) - ->setTitleVisible(true) - ->setPreviewCondition($previewCondition) - ->setParent(static::EDIT_FORM_VIEW . '_' . $typeKey) - ); - $viewCollection->add( - $this->viewBuilderFactory->createPreviewFormViewBuilder(static::EDIT_FORM_VIEW_SETTINGS . '_' . $typeKey, '/settings') - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->setFormKey('article_settings') - ->setTabTitle('sulu_page.settings') - ->setTabPriority(512) - ->addToolbarActions($formToolbarActionsWithoutType) - ->setTitleVisible(true) - ->setPreviewCondition($previewCondition) - ->setParent(static::EDIT_FORM_VIEW . '_' . $typeKey) - ); - - if ($this->automationViewBuilderFactory - && $this->securityChecker->hasPermission(AutomationAdmin::SECURITY_CONTEXT, PermissionTypes::EDIT) - ) { - $viewCollection->add( - $this->automationViewBuilderFactory->createTaskListViewBuilder( - static::EDIT_FORM_VIEW_AUTOMATION . '_' . $typeKey, - '/automation', - BasePageDocument::class - )->setParent(static::EDIT_FORM_VIEW . '_' . $typeKey) - ); - } - - if ($this->securityChecker->hasPermission(ActivityAdmin::SECURITY_CONTEXT, PermissionTypes::VIEW)) { - $viewCollection->add( - $this->viewBuilderFactory - ->createResourceTabViewBuilder(static::EDIT_FORM_VIEW_ACTIVITY . '_' . $typeKey, '/activity') - ->setResourceKey(ArticleDocument::RESOURCE_KEY) - ->setTabTitle($this->versioningEnabled ? 'sulu_admin.activity_versions' : 'sulu_admin.activity') - ->setTitleProperty('') - ->addRouterAttributesToBlacklist(['active', 'filter', 'limit', 'page', 'search', 'sortColumn', 'sortOrder']) - ->setParent(static::EDIT_FORM_VIEW . '_' . $typeKey) - ); - - $viewCollection->add( - $this->viewBuilderFactory - ->createListViewBuilder(static::EDIT_FORM_VIEW_ACTIVITY . '_' . $typeKey . '.activity', '/activity') - ->setTabTitle('sulu_admin.activity') - ->setResourceKey(ActivityInterface::RESOURCE_KEY) - ->setListKey('activities') - ->addListAdapters(['table']) - ->addAdapterOptions([ - 'table' => [ - 'skin' => 'flat', - 'show_header' => false, - ], - ]) - ->disableTabGap() - ->disableSearching() - ->disableSelection() - ->disableColumnOptions() - ->disableFiltering() - ->addResourceStorePropertiesToListRequest(['id' => 'resourceId']) - ->addRequestParameters(['resourceKey' => ArticleDocument::RESOURCE_KEY]) - ->setParent(static::EDIT_FORM_VIEW_ACTIVITY . '_' . $typeKey) - ); - - if ($this->versioningEnabled) { - $viewCollection->add( - $this->viewBuilderFactory - ->createListViewBuilder(static::EDIT_FORM_VIEW_ACTIVITY . '_' . $typeKey . '.versions', '/versions') - ->setTabTitle('sulu_admin.versions') - ->setResourceKey('article_versions') - ->setListKey('article_versions') - ->addListAdapters(['table']) - ->addAdapterOptions([ - 'table' => [ - 'skin' => 'flat', - ], - ]) - ->disableTabGap() - ->disableSearching() - ->disableSelection() - ->disableColumnOptions() - ->disableFiltering() - ->addRouterAttributesToListRequest(['id', 'webspace']) - ->addItemActions([ - new ListItemAction('restore_version', ['success_view' => static::EDIT_FORM_VIEW . '_' . $typeKey]), - ]) - ->setParent(static::EDIT_FORM_VIEW_ACTIVITY . '_' . $typeKey) - ); - } - } - } - } - - public function getSecurityContexts() - { - $securityContext = []; - - foreach ($this->getTypes() as $typeKey => $type) { - $securityContext[static::getArticleSecurityContext($typeKey)] = [ - PermissionTypes::VIEW, - PermissionTypes::ADD, - PermissionTypes::EDIT, - PermissionTypes::DELETE, - PermissionTypes::LIVE, - ]; - } - - return [ - 'Sulu' => [ - 'Global' => [ - static::SECURITY_CONTEXT => [ - PermissionTypes::VIEW, - PermissionTypes::ADD, - PermissionTypes::EDIT, - PermissionTypes::DELETE, - PermissionTypes::LIVE, - ], - ], - 'Article types' => $securityContext, - ], - ]; - } - - private function getTypes(): array - { - $types = []; - - // prefill array with keys from configuration to keep order of configuration for tabs - foreach ($this->articleTypeConfigurations as $typeKey => $articleTypeConfiguration) { - $types[$typeKey] = []; - } - - /** @var StructureBridge $structure */ - foreach ($this->structureManager->getStructures('article') as $structure) { - $type = $this->getType($structure->getStructure(), null); - $typeKey = $type ?: 'default'; - if (empty($types[$typeKey])) { - $types[$typeKey] = [ - 'type' => $type, - 'default' => $structure->getKey(), - 'title' => $this->getTitle($typeKey), - 'templates' => [], - ]; - } - - $types[$typeKey]['templates'][$structure->getKey()] = [ - 'multipage' => $this->getMultipage($structure->getStructure()), - ]; - } - - return $types; - } - - private function getTitle(string $type): string - { - if (!\array_key_exists($type, $this->articleTypeConfigurations)) { - return \ucfirst($type); - } - - return $this->articleTypeConfigurations[$type]['translation_key']; - } - - /** - * Returns security context for pages in given webspace. - * - * @final - */ - public static function getArticleSecurityContext(string $typeKey): string - { - return \sprintf('%s_%s', static::SECURITY_CONTEXT, $typeKey); - } -} diff --git a/Admin/Helper/WebspaceSelect.php b/Admin/Helper/WebspaceSelect.php deleted file mode 100644 index 118b63ce7..000000000 --- a/Admin/Helper/WebspaceSelect.php +++ /dev/null @@ -1,40 +0,0 @@ -webspaceManager = $webspaceManager; - } - - public function getValues(): array - { - $values = []; - foreach ($this->webspaceManager->getWebspaceCollection() as $webspace) { - $values[] = [ - 'name' => $webspace->getKey(), - 'title' => $webspace->getName(), - ]; - } - - return $values; - } -} diff --git a/Builder/ArticleIndexBuilder.php b/Builder/ArticleIndexBuilder.php deleted file mode 100644 index 4d09db646..000000000 --- a/Builder/ArticleIndexBuilder.php +++ /dev/null @@ -1,62 +0,0 @@ -buildForManager($this->container->get('es.manager.live'), $this->input->getOption('destroy')); - $this->buildForManager($this->container->get('es.manager.default'), $this->input->getOption('destroy')); - } - - /** - * Build index for given manager. - * - * If index not exists - it will be created. - * If index exists and destroy flag is true - drop and create index. - * Else do nothing. - */ - private function buildForManager(Manager $manager, bool $destroy): void - { - $name = $manager->getName(); - if (!$manager->indexExists()) { - $this->output->writeln(\sprintf('Create index for "%s" manager.', $name)); - $manager->createIndex(); - - return; - } - - if (!$destroy) { - return; - } - - $this->output->writeln(\sprintf('Drop and create index for "%s" manager.', $name)); - $manager->dropAndCreateIndex(); - } -} diff --git a/Command/ArticleExportCommand.php b/Command/ArticleExportCommand.php deleted file mode 100644 index 7c8381557..000000000 --- a/Command/ArticleExportCommand.php +++ /dev/null @@ -1,87 +0,0 @@ -articleExporter = $articleExporter; - } - - protected function configure(): void - { - $this->addArgument('target', InputArgument::REQUIRED, 'export.xliff') - ->addArgument('locale', InputArgument::REQUIRED) - ->addOption('format', 'f', InputOption::VALUE_REQUIRED, '', '1.2.xliff') - ->setDescription('Export article translations from given language into xliff file for translating into a new language.'); - } - - protected function execute(InputInterface $input, OutputInterface $output): int - { - $target = $input->getArgument('target'); - if (0 === !\strpos($target, '/')) { - $target = \getcwd() . '/' . $target; - } - $locale = $input->getArgument('locale'); - $format = $input->getOption('format'); - - $output->writeln([ - 'Article Language Export', - '=======================', - '', - 'Options', - 'Target: ' . $target, - 'Locale: ' . $locale, - 'Format: ' . $format, - '---------------', - '', - ]); - - $helper = $this->getHelper('question'); - $question = new ConfirmationQuestion('Continue with this options?(y/n) ', false); - - if (!$helper->ask($input, $output, $question)) { - $output->writeln('Abort!'); - - return 0; - } - - $output->writeln('Continue!'); - - $file = $this->articleExporter->export($locale, $format, $output); - - \file_put_contents($target, $file); - - return 0; - } -} diff --git a/Command/ArticleImportCommand.php b/Command/ArticleImportCommand.php deleted file mode 100644 index f0eb8a286..000000000 --- a/Command/ArticleImportCommand.php +++ /dev/null @@ -1,144 +0,0 @@ -articleImporter = $articleImporter; - $this->logger = $logger ?: new NullLogger(); - } - - protected function configure(): void - { - $this->addArgument('file', InputArgument::REQUIRED, 'export.xliff') - ->addArgument('locale', InputArgument::REQUIRED) - ->addOption('format', 'f', InputOption::VALUE_REQUIRED, '', '1.2.xliff') - ->addOption('uuid', 'u', InputOption::VALUE_REQUIRED) - ->addOption('overrideSettings', 'o', InputOption::VALUE_NONE, 'Override Settings-Tab') - ->setDescription('Import article translations from xliff file into a specific language.'); - } - - protected function execute(InputInterface $input, OutputInterface $output): int - { - $filePath = $input->getArgument('file'); - if (0 === !\strpos($filePath, '/')) { - $filePath = \getcwd() . '/' . $filePath; - } - $locale = $input->getArgument('locale'); - $format = $input->getOption('format'); - $overrideSettings = $input->getOption('overrideSettings'); - - $output->writeln([ - 'Language Import', - '===============', - '', - 'Options', - 'Locale: ' . $locale, - 'Format: ' . $format, - 'Override Setting: ' . ($overrideSettings ? 'YES' : 'NO'), - '---------------', - '', - ]); - - $helper = $this->getHelper('question'); - $question = new ConfirmationQuestion('Continue with this options? Be careful! (y/n) ', false); - - if (!$helper->ask($input, $output, $question)) { - $output->writeln('Abort!'); - - return -1; - } - - $output->writeln('Continue!'); - - $import = $this->articleImporter->import( - $locale, - $filePath, - $output, - $format, - $overrideSettings - ); - - if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { - $output->writeln(\sprintf('Imported %s/%s', $import->getSuccesses(), $import->getCount())); - } - - $this->printExceptions($import, $output); - - return $import->getFails(); - } - - protected function printExceptions(ImportResult $import, $output = null) - { - if (null === $output) { - $output = new NullOutput(); - } - - $output->writeln([ - '', - '', - 'Import Result', - '===============', - '' . $import->getSuccesses() . ' Documents imported.', - '' . \count($import->getFailed()) . ' Documents ignored.', - ]); - - if (!isset($import->getExceptionStore()['ignore'])) { - return; - } - - // If more than 20 exceptions write only into log. - if (\count($import->getExceptionStore()['ignore']) > 20) { - foreach ($import->getExceptionStore()['ignore'] as $msg) { - $this->logger->info($msg); - } - - return; - } - - foreach ($import->getExceptionStore()['ignore'] as $msg) { - $output->writeln('' . $msg . ''); - $this->logger->info($msg); - } - } -} diff --git a/Command/ReindexCommand.php b/Command/ReindexCommand.php deleted file mode 100644 index ca15552af..000000000 --- a/Command/ReindexCommand.php +++ /dev/null @@ -1,237 +0,0 @@ -webspaceManager = $webspaceManager; - $this->propertyEncoder = $propertyEncoder; - $this->documentManager = $documentManager; - $this->draftIndexer = $draftIndexer; - $this->liveIndexer = $liveIndexer; - $this->suluContext = $suluContext; - } - - public function configure(): void - { - $this->setDescription('Rebuild elastic-search index for articles'); - $this->setHelp('This command will load all articles and index them to elastic-search indexes.'); - $this->addOption('drop', null, InputOption::VALUE_NONE, 'Drop and recreate index before reindex'); - $this->addOption('clear', null, InputOption::VALUE_NONE, 'Clear all articles of index before reindex'); - } - - protected function execute(InputInterface $input, OutputInterface $output): int - { - $startTime = \microtime(true); - - $indexer = SuluKernel::CONTEXT_WEBSITE === $this->suluContext - ? $this->liveIndexer - : $this->draftIndexer; - - $output->writeln( - \sprintf('Reindex articles for the `%s` context' . \PHP_EOL, $this->suluContext) - ); - - if (!$this->dropIndex($indexer, $input, $output)) { - // Drop was canceled by user. - - return 0; - } - - $indexer->createIndex(); - $this->clearIndex($indexer, $input, $output); - - $locales = $this->webspaceManager->getAllLocalizations(); - - foreach ($locales as $locale) { - $output->writeln(\sprintf('Locale "%s"' . \PHP_EOL, $locale->getLocale())); - - $this->indexDocuments($locale->getLocale(), $indexer, $output); - - $output->writeln(\PHP_EOL); - } - - $output->writeln( - \sprintf( - 'Index rebuild completed (%ss %s)', - \number_format(\microtime(true) - $startTime, 2), - $this->humanBytes(\memory_get_peak_usage()) - ) - ); - - return 0; - } - - /** - * Drop index if requested. - */ - protected function dropIndex(IndexerInterface $indexer, InputInterface $input, OutputInterface $output): bool - { - if (!$input->getOption('drop')) { - return true; - } - - if (!$input->getOption('no-interaction')) { - $output->writeln( - 'ATTENTION: This operation drops and recreates the whole index and deletes the complete data.' - ); - $output->writeln(''); - - $question = new ConfirmationQuestion('Are you sure you want to drop the index? [Y/n] '); - - /** @var QuestionHelper $questionHelper */ - $questionHelper = $this->getHelper('question'); - if (!$questionHelper->ask($input, $output, $question)) { - return false; - } - - $output->writeln(''); - } - - $indexer->dropIndex(); - - $output->writeln( - \sprintf( - 'Dropped and recreated index for the `%s` context' . \PHP_EOL, - $this->suluContext - ) - ); - - return true; - } - - /** - * Clear article-content of index. - */ - protected function clearIndex(IndexerInterface $indexer, InputInterface $input, OutputInterface $output): void - { - if (!$input->getOption('clear')) { - return; - } - - $output->writeln(\sprintf('Cleared index for the `%s` context', $this->suluContext)); - $indexer->clear(); - } - - /** - * Index documents for given locale. - */ - protected function indexDocuments(string $locale, IndexerInterface $indexer, OutputInterface $output): void - { - $documents = $this->getDocuments($locale); - $count = \count($documents); - if (0 === $count) { - $output->writeln(' No documents found'); - - return; - } - - $progressBar = new ProgressBar($output, $count); - $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%'); - $progressBar->start(); - - foreach ($documents as $document) { - $indexer->index($document); - $progressBar->advance(); - } - - $indexer->flush(); - $progressBar->finish(); - } - - /** - * Query for documents with given locale. - */ - protected function getDocuments(string $locale): QueryResultCollection - { - $sql2 = \sprintf( - 'SELECT * FROM [nt:unstructured] AS a WHERE [jcr:mixinTypes] = "sulu:article" AND [%s] IS NOT NULL', - $this->propertyEncoder->localizedSystemName('template', $locale) - ); - - return $this->documentManager->createQuery($sql2, $locale, ['load_ghost_content' => false])->execute(); - } - - /** - * Converts bytes into human readable. - * - * Inspired by http://jeffreysambells.com/2012/10/25/human-readable-filesize-php - */ - protected function humanBytes(int $bytes, int $dec = 2): string - { - $size = ['b', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - $factor = (int) \floor((\strlen($bytes) - 1) / 3); - - return \sprintf("%.{$dec}f", $bytes / \pow(1024, $factor)) . $size[$factor]; - } -} diff --git a/Content/ArticleDataItem.php b/Content/ArticleDataItem.php deleted file mode 100644 index 573594fc2..000000000 --- a/Content/ArticleDataItem.php +++ /dev/null @@ -1,71 +0,0 @@ -id = $id; - $this->title = $title; - $this->resource = $resource; - } - - public function getId() - { - return $this->id; - } - - public function getTitle() - { - return $this->title; - } - - public function getResource() - { - return $this->resource; - } - - public function getImage() - { - return; - } -} diff --git a/Content/ArticleDataProvider.php b/Content/ArticleDataProvider.php deleted file mode 100644 index 8340d9ae9..000000000 --- a/Content/ArticleDataProvider.php +++ /dev/null @@ -1,563 +0,0 @@ -searchManager = $searchManager; - $this->documentManager = $documentManager; - $this->proxyFactory = $proxyFactory; - $this->referenceStore = $referenceStore; - $this->articleResourceItemFactory = $articleResourceItemFactory; - $this->articleDocumentClass = $articleDocumentClass; - $this->defaultLimit = $defaultLimit; - $this->formMetadataProvider = $formMetadataProvider; - $this->tokenStorage = $tokenStorage; - $this->hasAudienceTargeting = $hasAudienceTargeting; - } - - public function getConfiguration() - { - return $this->getConfigurationBuilder()->getConfiguration(); - } - - /** - * Create new configuration-builder. - */ - protected function getConfigurationBuilder(): BuilderInterface - { - $builder = Builder::create() - ->enableTags() - ->enableCategories() - ->enableLimit() - ->enablePagination() - ->enablePresentAs() - ->enableSorting( - [ - ['column' => 'published', 'title' => 'sulu_admin.published'], - ['column' => 'authored', 'title' => 'sulu_admin.authored'], - ['column' => 'created', 'title' => 'sulu_admin.created'], - ['column' => 'title.raw', 'title' => 'sulu_admin.title'], - ['column' => 'author_full_name.raw', 'title' => 'sulu_admin.author'], - ['column' => 'last_modified_or_authored', 'title' => 'sulu_article.last_modified_or_authored'], - ] - ); - - if (\method_exists($builder, 'enableTypes')) { - $builder->enableTypes($this->getTypes()); - } - - if ($this->hasAudienceTargeting) { - $builder->enableAudienceTargeting(); - } - - return $builder; - } - - public function getDefaultPropertyParameter() - { - return [ - 'type' => new PropertyParameter('type', null), - 'ignoreWebspaces' => new PropertyParameter('ignoreWebspaces', false), - ]; - } - - public function resolveDataItems( - array $filters, - array $propertyParameter, - array $options = [], - $limit = null, - $page = 1, - $pageSize = null - ) { - // there are two different kinds of types in the context of the article bundle: template-type and article-type - // filtering by article-type is possible via the types xml param - // filtering by template-type is possible via the structureTypes xml param and the admin interface overlay - // unfortunately, the admin frontend sends the selected types in $filters['types'] to the provider - // TODO: adjust the naming of the xml params to be consistent consistent, but this will be a bc break - $filters['structureTypes'] = \array_merge($filters['types'] ?? [], $this->getStructureTypesProperty($propertyParameter)); - $filters['types'] = $this->getTypesProperty($propertyParameter); - $filters['excluded'] = $this->getExcludedFilter($filters, $propertyParameter); - - /** @var string|null $locale */ - $locale = $options['locale']; - $webspaceKey = $this->getWebspaceKey($propertyParameter, $options); - $queryResult = $this->getSearchResult($filters, $limit, $page, $pageSize, $locale, $webspaceKey); - - $result = []; - /** @var ArticleViewDocumentInterface $document */ - foreach ($queryResult as $document) { - $result[] = new ArticleDataItem($document->getUuid(), $document->getTitle(), $document); - } - - return new DataProviderResult($result, $this->hasNextPage($queryResult, $limit, $page, $pageSize)); - } - - public function resolveResourceItems( - array $filters, - array $propertyParameter, - array $options = [], - $limit = null, - $page = 1, - $pageSize = null - ) { - // there are two different kinds of types in the context of the article bundle: template-type and article-type - // filtering by article-type is possible via the types xml param - // filtering by template-type is possible via the structureTypes xml param and the admin interface overlay - // unfortunately, the admin frontend sends the selected types in $filters['types'] to the provider - // TODO: adjust the naming of the xml params to be consistent consistent, but this will be a bc break - $filters['structureTypes'] = \array_merge($filters['types'] ?? [], $this->getStructureTypesProperty($propertyParameter)); - $filters['types'] = $this->getTypesProperty($propertyParameter); - $filters['excluded'] = $this->getExcludedFilter($filters, $propertyParameter); - - /** @var string|null $locale */ - $locale = $options['locale']; - $webspaceKey = $this->getWebspaceKey($propertyParameter, $options); - $queryResult = $this->getSearchResult($filters, $limit, $page, $pageSize, $locale, $webspaceKey); - - $result = []; - /** @var ArticleViewDocumentInterface $document */ - foreach ($queryResult as $document) { - $this->referenceStore->add($document->getUuid()); - $result[] = $this->articleResourceItemFactory->createResourceItem($document); - } - - return new DataProviderResult($result, $this->hasNextPage($queryResult, $limit, $page, $pageSize)); - } - - public function resolveDatasource($datasource, array $propertyParameter, array $options) - { - return; - } - - private function getWebspaceKey(array $propertyParameter, array $options): ?string - { - if (\array_key_exists('ignoreWebspaces', $propertyParameter)) { - $value = $propertyParameter['ignoreWebspaces']->getValue(); - - if (true === $value) { - return null; - } - } - - if (\array_key_exists('webspaceKey', $options)) { - return $options['webspaceKey']; - } - - return null; - } - - /** - * Returns flag "hasNextPage". - * It combines the limit/query-count with the page and page-size. - */ - private function hasNextPage(\Countable $queryResult, ?int $limit, int $page, ?int $pageSize): bool - { - $count = $queryResult->count(); - - if (null === $pageSize || $pageSize > $this->defaultLimit) { - $pageSize = $this->defaultLimit; - } - - $offset = ($page - 1) * $pageSize; - if ($limit && $offset + $pageSize > $limit) { - return false; - } - - return $count > ($page * $pageSize); - } - - /** - * Creates search for filters and returns search-result. - */ - private function getSearchResult(array $filters, ?int $limit, int $page, ?int $pageSize, ?string $locale, ?string $webspaceKey): \Countable - { - $repository = $this->searchManager->getRepository($this->articleDocumentClass); - $search = $this->createSearch($repository->createSearch(), $filters, $locale); - if (!$search) { - return new \ArrayIterator([]); - } - - $this->addPagination($search, $pageSize, $page, $limit); - - if (\array_key_exists('sortBy', $filters)) { - $sortMethod = \array_key_exists('sortMethod', $filters) ? $filters['sortMethod'] : 'asc'; - $search->addSort(new FieldSort($filters['sortBy'], $sortMethod)); - } - - if ($webspaceKey) { - $webspaceQuery = new BoolQuery(); - - // check for mainWebspace - $webspaceQuery->add(new TermQuery('main_webspace', $webspaceKey), BoolQuery::SHOULD); - - // check for additionalWebspaces - $webspaceQuery->add(new TermQuery('additional_webspaces', $webspaceKey), BoolQuery::SHOULD); - - $search->addQuery($webspaceQuery); - } - - $segmentKey = $filters['segmentKey'] ?? null; - if ($segmentKey && $webspaceKey) { - $matchingSegmentQuery = new TermQuery( - 'excerpt.segments.assignment_key', - $webspaceKey . SegmentSelect::SEPARATOR . $segmentKey - ); - - $noSegmentQuery = new BoolQuery(); - $noSegmentQuery->add(new TermQuery('excerpt.segments.webspace_key', $webspaceKey), BoolQuery::MUST_NOT); - - $segmentQuery = new BoolQuery(); - $segmentQuery->add($matchingSegmentQuery, BoolQuery::SHOULD); - $segmentQuery->add($noSegmentQuery, BoolQuery::SHOULD); - - $search->addQuery($segmentQuery); - } - - $targetGroup = $filters['targetGroupId'] ?? null; - - if ($targetGroup) { - $targetGroupQuery = new BoolQuery(); - $targetGroupQuery->add(new TermQuery('excerpt.audience_targeting_groups', $targetGroup), BoolQuery::MUST); - $search->addQuery($targetGroupQuery); - } - - return $repository->findDocuments($search); - } - - /** - * Initialize search with neccesary queries. - */ - protected function createSearch(Search $search, array $filters, string $locale): Search - { - if (0 < \count($filters['excluded'])) { - foreach ($filters['excluded'] as $uuid) { - $search->addQuery(new TermQuery('uuid', $uuid), BoolQuery::MUST_NOT); - } - } - - $query = new BoolQuery(); - - $queriesCount = 0; - $operator = $this->getFilter($filters, 'tagOperator', 'or'); - $this->addBoolQuery('tags', $filters, 'excerpt.tags.id', $operator, $query, $queriesCount); - $operator = $this->getFilter($filters, 'websiteTagsOperator', 'or'); - $this->addBoolQuery('websiteTags', $filters, 'excerpt.tags.id', $operator, $query, $queriesCount); - - $operator = $this->getFilter($filters, 'categoryOperator', 'or'); - $this->addBoolQuery('categories', $filters, 'excerpt.categories.id', $operator, $query, $queriesCount); - $operator = $this->getFilter($filters, 'websiteCategoriesOperator', 'or'); - $this->addBoolQuery('websiteCategories', $filters, 'excerpt.categories.id', $operator, $query, $queriesCount); - - if (null !== $locale) { - $search->addQuery(new TermQuery('locale', $locale)); - } - - if (\array_key_exists('types', $filters) && $filters['types']) { - $typesQuery = new BoolQuery(); - foreach ($filters['types'] as $typeFilter) { - $typesQuery->add(new TermQuery('type', $typeFilter), BoolQuery::SHOULD); - } - $search->addQuery($typesQuery); - } - - if (\array_key_exists('structureTypes', $filters) && $filters['structureTypes']) { - $strTypesQuery = new BoolQuery(); - foreach ($filters['structureTypes'] as $filter) { - $strTypesQuery->add(new TermQuery('structure_type', $filter), BoolQuery::SHOULD); - } - $search->addQuery($strTypesQuery); - } - - if (0 === $queriesCount) { - $search->addQuery(new MatchAllQuery(), BoolQuery::MUST); - } else { - $search->addQuery($query, BoolQuery::MUST); - } - - return $search; - } - - /** - * Returns array with all types defined in property parameter. - */ - private function getTypesProperty(array $propertyParameter): array - { - $filterTypes = []; - - if (\array_key_exists('types', $propertyParameter) - && !empty($value = $propertyParameter['types']->getValue()) - && \is_string($value)) { - $types = \explode(',', $value); - - foreach ($types as $type) { - $filterTypes[] = $type; - } - } - - return $filterTypes; - } - - /** - * Returns array with all structure types (template keys) defined in property parameter. - */ - private function getStructureTypesProperty(array $propertyParameter): array - { - $filterStrTypes = []; - - if (\array_key_exists('structureTypes', $propertyParameter) - && null !== ($types = \explode(',', $propertyParameter['structureTypes']->getValue())) - ) { - foreach ($types as $type) { - $filterStrTypes[] = $type; - } - } - - return $filterStrTypes; - } - - /** - * Returns excluded articles. - * - * @param PropertyParameter[] $propertyParameter - */ - private function getExcludedFilter(array $filters, array $propertyParameter): array - { - $excluded = \array_key_exists('excluded', $filters) ? $filters['excluded'] : []; - if (\array_key_exists('exclude_duplicates', $propertyParameter) - && $propertyParameter['exclude_duplicates']->getValue() - ) { - $excluded = \array_merge($excluded, $this->referenceStore->getAll()); - } - - return $excluded; - } - - /** - * Add the pagination to given query. - */ - private function addPagination(Search $search, ?int $pageSize, int $page, ?int $limit): void - { - if (null === $pageSize || $pageSize > $this->defaultLimit) { - $pageSize = $this->defaultLimit; - } - - $offset = ($page - 1) * $pageSize; - - if ($limit && $offset + $pageSize > $limit) { - $pageSize = $limit - $offset; - } - - if ($pageSize < 0) { - $pageSize = 0; - } - - $search->setFrom($offset); - $search->setSize($pageSize); - } - - /** - * Add a boolean-query if filter exists. - */ - private function addBoolQuery( - string $filterName, - array $filters, - string $field, - string $operator, - BoolQuery $query, - int &$queriesCount - ): void { - if (0 !== \count($tags = $this->getFilter($filters, $filterName, []))) { - ++$queriesCount; - $query->add($this->getBoolQuery($field, $tags, $operator)); - } - } - - /** - * Returns boolean query for given fields and values. - */ - private function getBoolQuery(string $field, array $values, string $operator): BoolQuery - { - $type = ('or' === \strtolower($operator) ? BoolQuery::SHOULD : BoolQuery::MUST); - - $query = new BoolQuery(); - foreach ($values as $value) { - $query->add(new TermQuery($field, $value), $type); - } - - return $query; - } - - /** - * Returns filter value. - * - * @param mixed $default - * - * @return mixed - */ - private function getFilter(array $filters, string $name, $default = null) - { - if ($this->hasFilter($filters, $name)) { - return $filters[$name]; - } - - return $default; - } - - /** - * @return array> - */ - private function getTypes(): array - { - $types = []; - if ($this->tokenStorage && null !== $this->tokenStorage->getToken() && $this->formMetadataProvider) { - $user = $this->tokenStorage->getToken()->getUser(); - - if (!$user instanceof UserInterface) { - return $types; - } - - /** @var TypedFormMetadata $metadata */ - $metadata = $this->formMetadataProvider->getMetadata('article', $user->getLocale(), []); - - foreach ($metadata->getForms() as $form) { - $types[] = ['type' => $form->getName(), 'title' => $form->getTitle()]; - } - } - - return $types; - } - - /** - * Returns true if filter-value exists. - */ - private function hasFilter(array $filters, string $name): bool - { - return \array_key_exists($name, $filters) && null !== $filters[$name]; - } - - /** - * Returns Proxy document for uuid. - */ - private function getResource(string $uuid, string $locale): object - { - return $this->proxyFactory->createProxy( - ArticleDocument::class, - function( - &$wrappedObject, - LazyLoadingInterface $proxy, - $method, - array $parameters, - &$initializer - ) use ($uuid, $locale) { - $initializer = null; - $wrappedObject = $this->documentManager->find($uuid, $locale); - - return true; - } - ); - } - - public function getAlias() - { - return 'article'; - } -} diff --git a/Content/ArticleResourceItem.php b/Content/ArticleResourceItem.php deleted file mode 100644 index c533a2ab4..000000000 --- a/Content/ArticleResourceItem.php +++ /dev/null @@ -1,198 +0,0 @@ -article = $article; - $this->resource = $resource; - } - - /** - * Returns uuid. - */ - public function getUuid(): string - { - return $this->article->getUuid(); - } - - /** - * Returns locale. - */ - public function getLocale(): string - { - return $this->article->getLocale(); - } - - /** - * Returns title. - */ - public function getTitle(): string - { - return $this->article->getTitle(); - } - - /** - * Returns type. - */ - public function getType(): string - { - return $this->article->getType(); - } - - /** - * Returns changer. - */ - public function getChanger(): string - { - return $this->article->getChangerFullName(); - } - - /** - * Returns creator. - */ - public function getCreator(): string - { - return $this->article->getCreatorFullName(); - } - - /** - * Return changed. - */ - public function getChanged(): \DateTime - { - return $this->article->getChanged(); - } - - /** - * Returns created. - */ - public function getCreated(): \DateTime - { - return $this->article->getCreated(); - } - - /** - * Returns published. - */ - public function getPublished(): \DateTime - { - return $this->article->getPublished(); - } - - /** - * Returns lastModified. - */ - public function getLastModified(): ?\DateTime - { - return $this->article->getLastModified(); - } - - /** - * Returns authored. - */ - public function getAuthored(): \DateTime - { - return $this->article->getAuthored(); - } - - /** - * Returns excerpt. - */ - public function getExcerpt(): ExcerptViewObject - { - return $this->article->getExcerpt(); - } - - /** - * Returns seo. - */ - public function getSeo(): SeoViewObject - { - return $this->article->getSeo(); - } - - /** - * Returns route-path. - */ - public function getRoutePath(): string - { - return $this->article->getRoutePath(); - } - - /** - * Returns view-object. - */ - public function getContent(): ArticleViewDocumentInterface - { - return $this->article; - } - - public function getTargetWebspace(): string - { - return $this->article->getTargetWebspace(); - } - - public function getMainWebspace(): string - { - return $this->article->getMainWebspace(); - } - - /** - * @return string[]|null - */ - public function getAdditionalWebspaces(): ?array - { - return $this->article->getAdditionalWebspaces(); - } - - public function getResource() - { - return $this->resource; - } - - public function getId() - { - return $this->getUuid(); - } - - public function getAuthorId() - { - return $this->article->getAuthorId(); - } - - public function getAuthorFullName() - { - return $this->article->getAuthorFullName(); - } -} diff --git a/Content/ArticleResourceItemFactory.php b/Content/ArticleResourceItemFactory.php deleted file mode 100644 index 9e94cadf7..000000000 --- a/Content/ArticleResourceItemFactory.php +++ /dev/null @@ -1,75 +0,0 @@ -documentManager = $documentManager; - $this->proxyFactory = $proxyFactory; - } - - /** - * Creates and returns article source item with proxy document. - */ - public function createResourceItem(ArticleViewDocumentInterface $articleViewDocument): ArticleResourceItem - { - return new ArticleResourceItem( - $articleViewDocument, - $this->getResource($articleViewDocument->getUuid(), $articleViewDocument->getLocale()) - ); - } - - /** - * Returns Proxy document for uuid. - */ - private function getResource(string $uuid, string $locale): object - { - return $this->proxyFactory->createProxy( - ArticleDocument::class, - function( - &$wrappedObject, - LazyLoadingInterface $proxy, - $method, - array $parameters, - &$initializer - ) use ($uuid, $locale) { - $initializer = null; - $wrappedObject = $this->documentManager->find($uuid, $locale); - - return true; - } - ); - } -} diff --git a/Content/ArticleSelectionContentType.php b/Content/ArticleSelectionContentType.php deleted file mode 100644 index ee538a9d2..000000000 --- a/Content/ArticleSelectionContentType.php +++ /dev/null @@ -1,93 +0,0 @@ -searchManager = $searchManager; - $this->referenceStore = $referenceStore; - $this->articleDocumentClass = $articleDocumentClass; - } - - public function getContentData(PropertyInterface $property) - { - $value = $property->getValue(); - if (null === $value || !\is_array($value) || 0 === \count($value)) { - return []; - } - - $locale = $property->getStructure()->getLanguageCode(); - - $repository = $this->searchManager->getRepository($this->articleDocumentClass); - $search = $repository->createSearch(); - $search->addQuery(new IdsQuery($this->getViewDocumentIds($value, $locale))); - $search->setSize(\count($value)); - - $result = []; - /** @var ArticleViewDocumentInterface $articleDocument */ - foreach ($repository->findDocuments($search) as $articleDocument) { - $result[\array_search($articleDocument->getUuid(), $value, false)] = $articleDocument; - } - - \ksort($result); - - return \array_values($result); - } - - public function preResolve(PropertyInterface $property) - { - $uuids = $property->getValue(); - if (!\is_array($uuids)) { - return; - } - - foreach ($uuids as $uuid) { - $this->referenceStore->add($uuid); - } - } -} diff --git a/Content/PageTreeArticleDataProvider.php b/Content/PageTreeArticleDataProvider.php deleted file mode 100644 index b49660ef5..000000000 --- a/Content/PageTreeArticleDataProvider.php +++ /dev/null @@ -1,75 +0,0 @@ -getConfigurationBuilder() - ->enableDatasource('pages', 'pages', 'column_list') - ->getConfiguration(); - } - - public function resolveDatasource($datasource, array $propertyParameter, array $options) - { - if (!$datasource) { - return null; - } - - /** @var string|null $locale */ - $locale = $options['locale']; - $document = $this->documentManager->find($datasource, $locale); - - if (!$document instanceof BasePageDocument) { - return null; - } - - return new DatasourceItem($document->getUuid(), $document->getTitle(), $document->getResourceSegment()); - } - - protected function createSearch(Search $search, array $filters, string $locale): Search - { - $search = parent::createSearch($search, $filters, $locale); - - if (!\array_key_exists('dataSource', $filters) || !$filters['dataSource']) { - return $search; - } - - $document = $this->documentManager->find($filters['dataSource'], $locale); - - if (!$document instanceof BasePageDocument || !$document->getResourceSegment()) { - return $search; - } - - $includeSubFolders = $filters['includeSubFolders'] ?? null; - - if (true === $includeSubFolders) { - $search->addQuery(new PrefixQuery('route_path.raw', \rtrim($document->getResourceSegment(), '/') . '/')); - - return $search; - } - - $search->addQuery(new TermQuery('parent_page_uuid', $document->getUuid())); - - return $search; - } -} diff --git a/Content/SingleArticleSelectionContentType.php b/Content/SingleArticleSelectionContentType.php deleted file mode 100644 index 0d422d0ae..000000000 --- a/Content/SingleArticleSelectionContentType.php +++ /dev/null @@ -1,78 +0,0 @@ -searchManager = $searchManager; - $this->referenceStore = $referenceStore; - $this->articleDocumentClass = $articleDocumentClass; - } - - public function getContentData(PropertyInterface $property) - { - $uuid = $property->getValue(); - - if (null === $uuid) { - return null; - } - - $repository = $this->searchManager->getRepository($this->articleDocumentClass); - $locale = $property->getStructure()->getLanguageCode(); - - return $repository->find($this->getViewDocumentId($uuid, $locale)) ?? null; - } - - public function preResolve(PropertyInterface $property) - { - $uuid = $property->getValue(); - if (null === $uuid) { - return; - } - - $this->referenceStore->add($uuid); - } -} diff --git a/Controller/ArticleController.php b/Controller/ArticleController.php deleted file mode 100644 index 0b011eaea..000000000 --- a/Controller/ArticleController.php +++ /dev/null @@ -1,753 +0,0 @@ -documentManager = $documentManager; - $this->contentMapper = $contentMapper; - $this->metadataFactory = $metadataFactory; - $this->restHelper = $restHelper; - $this->manager = $manager; - $this->documentFactory = $documentFactory; - $this->formFactory = $formFactory; - $this->requestHashChecker = $requestHashChecker; - $this->securityChecker = $securityChecker; - $this->displayTabAll = $displayTabAll; - $this->documentInspector = $documentInspector; - - if (null === $this->documentInspector) { - @trigger_deprecation('sulu/article-bundle', '2.5', 'Instantiating the ArticleController without the $documentInspector argument is deprecated!'); - } - } - - /** - * Create field-descriptor array. - * - * @return ElasticSearchFieldDescriptor[] - */ - protected function getFieldDescriptors(): array - { - return [ - 'uuid' => ElasticSearchFieldDescriptor::create('id', 'public.id') - ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO) - ->build(), - 'typeTranslation' => ElasticSearchFieldDescriptor::create('typeTranslation', 'sulu_article.list.type') - ->setSortField('typeTranslation.raw') - ->setVisibility( - $this->displayTabAll ? - FieldDescriptorInterface::VISIBILITY_YES : - FieldDescriptorInterface::VISIBILITY_NEVER - ) - ->build(), - 'title' => ElasticSearchFieldDescriptor::create('title', 'public.title') - ->setSortField('title.raw') - ->setSearchField('title') - ->setSearchability(FieldDescriptor::SEARCHABILITY_YES) - ->build(), - 'creatorFullName' => ElasticSearchFieldDescriptor::create('creatorFullName', 'sulu_article.list.creator') - ->setSortField('creatorFullName.raw') - ->build(), - 'changerFullName' => ElasticSearchFieldDescriptor::create('changerFullName', 'sulu_article.list.changer') - ->setSortField('changerFullName.raw') - ->build(), - 'authorFullName' => ElasticSearchFieldDescriptor::create('authorFullName', 'sulu_article.author') - ->setSortField('authorFullName.raw') - ->build(), - 'created' => ElasticSearchFieldDescriptor::create('created', 'public.created') - ->setSortField('created') - ->setType('datetime') - ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO) - ->build(), - 'changed' => ElasticSearchFieldDescriptor::create('changed', 'public.changed') - ->setSortField('changed') - ->setType('datetime') - ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO) - ->build(), - 'authored' => ElasticSearchFieldDescriptor::create('authored', 'sulu_article.authored') - ->setSortField('authored') - ->setType('datetime') - ->build(), - 'localizationState' => ElasticSearchFieldDescriptor::create('localizationState') - ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO) - ->build(), - 'published' => ElasticSearchFieldDescriptor::create('published') - ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO) - ->build(), - 'publishedState' => ElasticSearchFieldDescriptor::create('publishedState') - ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO) - ->build(), - 'routePath' => ElasticSearchFieldDescriptor::create('routePath') - ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO) - ->setSearchField('route_path.value') - ->setSearchability(FieldDescriptor::SEARCHABILITY_YES) - ->build(), - ]; - } - - /** - * Returns list of articles. - */ - public function cgetAction(Request $request): Response - { - $locale = $this->getRequestParameter($request, 'locale', true); - - $repository = $this->manager->getRepository($this->documentFactory->getClass('article')); - $search = $repository->createSearch(); - - $limit = (int) $this->restHelper->getLimit(); - $page = (int) $this->restHelper->getPage(); - - /** @var array{ - * authored?: array{ - * from: string, - * to: string, - * }, - * type?: string, - * contactId?: string, - * categoryId?: string, - * tagId?: string, - * pageId?: string, - * publishedState?: string, - * } $filter */ - $filter = $request->query->all()['filter'] ?? []; - - if (null !== $locale) { - $search->addQuery(new TermQuery('locale', $locale)); - } - - if (\count($ids = \array_filter(\explode(',', $request->get('ids', ''))))) { - $search->addQuery(new IdsQuery($this->getViewDocumentIds($ids, $locale))); - $limit = \count($ids); - } - - $fieldDescriptors = $this->getFieldDescriptors(); - - $searchFields = $this->restHelper->getSearchFields(); - if (0 === \count($searchFields)) { - foreach ($fieldDescriptors as $fieldDescriptor) { - if (FieldDescriptorInterface::SEARCHABILITY_YES !== $fieldDescriptor->getSearchability()) { - continue; - } - - $searchFields[] = $fieldDescriptor->getSearchField(); - } - } - - $searchPattern = $this->restHelper->getSearchPattern(); - if (!empty($searchPattern)) { - $boolQuery = new BoolQuery(); - foreach ($searchFields as $searchField) { - $boolQuery->add(new MatchPhrasePrefixQuery($searchField, $searchPattern), BoolQuery::SHOULD); - } - $search->addQuery($boolQuery); - } - - if (null !== ($typeString = $request->get('types', $filter['type'] ?? null))) { - $types = \explode(',', $typeString); - - if (\count($types) > 1) { - $query = new BoolQuery(); - - foreach ($types as $type) { - $query->add(new TermQuery('type', $type), BoolQuery::SHOULD); - } - - $search->addQuery($query); - } elseif ($types[0]) { - $search->addQuery(new TermQuery('type', $types[0])); - } - } - - if ($contactId = $request->get('contactId', $filter['contactId'] ?? null)) { - $boolQuery = new BoolQuery(); - $boolQuery->add(new MatchQuery('changer_contact_id', $contactId), BoolQuery::SHOULD); - $boolQuery->add(new MatchQuery('creator_contact_id', $contactId), BoolQuery::SHOULD); - $boolQuery->add(new MatchQuery('author_id', $contactId), BoolQuery::SHOULD); - $search->addQuery($boolQuery); - } - - if ($categoryId = $request->get('categoryId', $filter['categoryId'] ?? null)) { - $search->addQuery(new TermQuery('excerpt.categories.id', $categoryId), BoolQuery::MUST); - } - - if ($tagId = $request->get('tagId', $filter['tagId'] ?? null)) { - $search->addQuery(new TermQuery('excerpt.tags.id', $tagId), BoolQuery::MUST); - } - - if ($pageId = $request->get('pageId', $filter['pageId'] ?? null)) { - $search->addQuery(new TermQuery('parent_page_uuid', $pageId), BoolQuery::MUST); - } - - if ($workflowStage = $request->get('workflowStage', $filter['publishedState'] ?? null)) { - $search->addQuery(new TermQuery('published_state', 'published' === $workflowStage), BoolQuery::MUST); - } - - if ($this->getBooleanRequestParameter($request, 'exclude-shadows', false, false)) { - $search->addQuery(new TermQuery('localization_state.state', 'shadow'), BoolQuery::MUST_NOT); - } - - if ($this->getBooleanRequestParameter($request, 'exclude-ghosts', false, false)) { - $search->addQuery(new TermQuery('localization_state.state', 'ghost'), BoolQuery::MUST_NOT); - } - - $authoredFrom = $request->get('authoredFrom', $this->convertDateTime($filter['authored']['from'] ?? null)); - $authoredTo = $request->get('authoredTo', $this->convertDateTime($filter['authored']['to'] ?? null)); - if ($authoredFrom || $authoredTo) { - $search->addQuery($this->getRangeQuery('authored', $authoredFrom, $authoredTo), BoolQuery::MUST); - } - - if (null === $search->getQueries()) { - $search->addQuery(new MatchAllQuery()); - } - - if (null !== $this->restHelper->getSortColumn() - && $sortField = $this->getSortFieldName($this->restHelper->getSortColumn()) - ) { - $search->addSort( - new FieldSort($sortField, $this->restHelper->getSortOrder()) - ); - } else { - $search->addSort( - new FieldSort('created', 'ASC') - ); - } - - if ($limit) { - $search->setSize($limit); - $search->setFrom(($page - 1) * $limit); - - $fields = \array_merge( - $this->restHelper->getFields() ?: [], - ['id', 'localizationState', 'publishedState', 'published', 'title', 'routePath'] - ); - $fieldDescriptors = \array_filter( - $fieldDescriptors, - function(FieldDescriptorInterface $fieldDescriptor) use ($fields) { - return \in_array($fieldDescriptor->getName(), $fields); - } - ); - } else { - $search->setSize(1000); - $search->setScroll('1m'); - } - - if (\method_exists($search, 'setTrackTotalHits')) { - $search->setTrackTotalHits(true); - } - - $searchResult = $repository->findRaw($search); - $result = []; - foreach ($searchResult as $document) { - $documentData = $this->normalize($document['_source'], $fieldDescriptors); - $documentData['ghostLocale'] = 'ghost' == $documentData['localizationState']['state'] ? $documentData['localizationState']['locale'] : null; - - if (false !== ($index = \array_search($documentData['id'], $ids))) { - $result[$index] = $documentData; - } else { - $result[] = $documentData; - } - } - - if (\count($ids)) { - \ksort($result); - $result = \array_values($result); - } - - $count = $searchResult->count(); - - return $this->handleView( - $this->view( - new ListRepresentation( - $result, - 'articles', - 'sulu_article.get_articles', - $request->query->all(), - $page, - $limit, - $count - ) - ) - ); - } - - /** - * @param FieldDescriptorInterface[] $fieldDescriptors - */ - private function normalize(array $document, array $fieldDescriptors) - { - $result = []; - foreach ($fieldDescriptors as $fieldDescriptor) { - $property = Caser::snake($fieldDescriptor->getName()); - if ('id' === $property) { - $property = 'uuid'; - } - - $result[$fieldDescriptor->getName()] = \array_key_exists($property, $document) ? $document[$property] : null; - } - - return $result; - } - - /** - * Returns query to filter by given range. - */ - private function getRangeQuery(string $field, string $from, string $to): RangeQuery - { - return new RangeQuery($field, \array_filter(['gte' => $from, 'lte' => $to])); - } - - /** - * Returns single article. - * - * @Get(defaults={"id" = ""}) - */ - public function getAction(Request $request, string $id): Response - { - $locale = $this->getRequestParameter($request, 'locale', true); - /** @var ArticleDocument $document */ - $document = $this->documentManager->find( - $id, - $locale - ); - - if ($this->documentInspector) { - $localizationState = $this->documentInspector->getLocalizationState($document); - - if (LocalizationState::GHOST === $localizationState) { - $document = $this->documentManager->find( - $id, - $locale, - [ - 'load_ghost_content' => false, - 'structure_type' => $document->getStructureType(), - ] - ); - } - } - - $context = new Context(); - $context->setSerializeNull(true); - $context->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage']); - - return $this->handleView( - $this->view($document)->setContext($context) - ); - } - - /** - * Create article. - */ - public function postAction(Request $request): Response - { - $action = $request->get('action'); - $document = $this->documentManager->create(self::DOCUMENT_TYPE); - $locale = $this->getRequestParameter($request, 'locale', true); - $data = $request->request->all(); - - $this->persistDocument($data, $document, $locale); - $this->handleActionParameter($action, $document, $locale); - $this->documentManager->flush(); - - $context = new Context(); - $context->setSerializeNull(true); - $context->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage']); - - return $this->handleView( - $this->view($document)->setContext($context) - ); - } - - /** - * Update articles. - */ - public function putAction(Request $request, string $id): Response - { - $locale = $this->getRequestParameter($request, 'locale', true); - $action = $request->get('action'); - $data = $request->request->all(); - - $document = $this->documentManager->find( - $id, - $locale, - [ - 'load_ghost_content' => false, - 'load_shadow_content' => false, - ] - ); - - $this->requestHashChecker->checkHash($request, $document, $document->getUuid()); - - $this->persistDocument($data, $document, $locale); - $this->handleActionParameter($action, $document, $locale); - $this->documentManager->flush(); - - $context = new Context(); - $context->setSerializeNull(true); - $context->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage']); - - return $this->handleView( - $this->view($document)->setContext($context) - ); - } - - /** - * Deletes multiple documents. - */ - public function cdeleteAction(Request $request): Response - { - $ids = \array_filter(\explode(',', $request->get('ids', ''))); - - $documentManager = $this->documentManager; - foreach ($ids as $id) { - $document = $documentManager->find($id); - $documentManager->remove($document); - $documentManager->flush(); - } - - return $this->handleView($this->view(null)); - } - - /** - * Deletes multiple documents. - */ - public function deleteAction(Request $request, string $id): Response - { - $locale = $this->getLocale($request); - $deleteLocale = $this->getBooleanRequestParameter($request, 'deleteLocale', false, false); - - $document = $this->documentManager->find($id); - if ($deleteLocale) { - $this->documentManager->removeLocale($document, $locale); - } else { - $this->documentManager->remove($document); - } - $this->documentManager->flush(); - - return $this->handleView($this->view(null)); - } - - /** - * Trigger a action for given article specified over get-action parameter. - * - * @Post("/articles/{id}") - */ - public function postTriggerAction(string $id, Request $request): Response - { - // extract parameter - $action = $this->getRequestParameter($request, 'action', true); - $locale = $this->getRequestParameter($request, 'locale', false); - - // prepare vars - $view = null; - $data = null; - $userId = $this->getUser()->getId(); - - try { - switch ($action) { - case 'unpublish': - $document = $this->documentManager->find($id, $locale); - $this->documentManager->unpublish($document, $locale); - $this->documentManager->flush(); - - $data = $this->documentManager->find($id, $locale); - - break; - case 'remove-draft': - $data = $this->documentManager->find($id, $locale); - $this->documentManager->removeDraft($data, $locale); - $this->documentManager->flush(); - - break; - case 'copy-locale': - $srcLocale = $this->getRequestParameter($request, 'src', false, $locale); - $destLocales = $this->getRequestParameter($request, 'dest', true); - $destLocales = \explode(',', $destLocales); - - foreach ($destLocales as $destLocale) { - $this->securityChecker->checkPermission( - new SecurityCondition($this->getSecurityContext(), $destLocale), - PermissionTypes::EDIT - ); - } - - $document = $this->documentManager->find($id, $srcLocale); - foreach ($destLocales as $destLocale) { - $this->documentManager->copyLocale($document, $srcLocale, $destLocale); - } - - $this->documentManager->flush(); - - $data = $this->documentManager->find($id, $locale); - - break; - case 'copy': - /** @var ArticleDocument $document */ - $document = $this->documentManager->find($id, $locale); - /** @var string $copiedPath */ - $copiedPath = $this->documentManager->copy($document, \dirname($document->getPath())); - $this->documentManager->flush(); - - $data = $this->documentManager->find($copiedPath, $locale); - - break; - case 'order': - $this->orderPages($this->getRequestParameter($request, 'pages', true), $locale); - $this->documentManager->flush(); - $this->documentManager->clear(); - - $data = $this->documentManager->find($id, $locale); - - break; - default: - throw new RestException('Unrecognized action: ' . $action); - } - - // create context - $context = new Context(); - $context->setSerializeNull(true); - $context->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage']); - - // prepare view - $view = $this->view($data); - $view->setContext($context); - } catch (RestException $exc) { - $view = $this->view($exc->toArray(), 400); - } - - return $this->handleView($view); - } - - /** - * Ordering given pages. - */ - private function orderPages(array $pages, string $locale): void - { - $documentManager = $this->documentManager; - - for ($i = 0; $i < \count($pages); ++$i) { - $document = $documentManager->find($pages[$i], $locale); - $documentManager->reorder($document, null); - } - } - - public function getSecurityContext() - { - return ArticleAdmin::SECURITY_CONTEXT; - } - - /** - * Persists the document using the given Formation. - * - * @throws InvalidFormException - * @throws MissingParameterException - */ - private function persistDocument(array $data, object $document, string $locale): void - { - /** @var class-string<\Symfony\Component\Form\FormTypeInterface> $formType */ - $formType = $this->metadataFactory->getMetadataForAlias('article')->getFormType(); - $form = $this->formFactory->create( - $formType, - $document, - [ - // disable csrf protection, since we can't produce a token, because the form is cached on the client - 'csrf_protection' => false, - ] - ); - $form->submit($data, false); - - if (!$form->isValid()) { - throw new InvalidFormException($form); - } - - if (\array_key_exists('author', $data) && null === $data['author']) { - $document->setAuthor(null); - } - - if (\array_key_exists('additionalWebspaces', $data) && null === $data['additionalWebspaces']) { - $document->setAdditionalWebspaces(null); - } - - if (\array_key_exists('customizeWebspaceSettings', $data) && false === $data['customizeWebspaceSettings']) { - $document->setMainWebspace(null); - $document->setAdditionalWebspaces(null); - } - - $this->documentManager->persist( - $document, - $locale, - [ - 'user' => $this->getUser()->getId(), - 'clear_missing_content' => false, - ] - ); - } - - /** - * Delegates actions by given actionParameter, which can be retrieved from the request. - */ - private function handleActionParameter(?string $actionParameter, object $document, string $locale): void - { - switch ($actionParameter) { - case 'publish': - $this->documentManager->publish($document, $locale); - - break; - } - } - - private function getSortFieldName(string $sortBy): ?string - { - $sortBy = Caser::snake($sortBy); - $fieldDescriptors = $this->getFieldDescriptors(); - - if (\array_key_exists($sortBy, $fieldDescriptors)) { - return $fieldDescriptors[$sortBy]->getSortField(); - } - - return null; - } - - private function convertDateTime(?string $dateTimeString): ?string - { - if (!$dateTimeString) { - return null; - } - - $dateTime = new \DateTime($dateTimeString); - - return $dateTime->format('Y-m-d'); - } -} diff --git a/Controller/ArticlePageController.php b/Controller/ArticlePageController.php deleted file mode 100644 index 95b075d86..000000000 --- a/Controller/ArticlePageController.php +++ /dev/null @@ -1,248 +0,0 @@ -documentManager = $documentManager; - $this->metadataFactory = $metadataFactory; - $this->formFactory = $formFactory; - $this->requestHashChecker = $requestHashChecker; - } - - /** - * Returns single article-page. - * - * @throws ArticlePageNotFoundException - */ - public function getAction(string $articleUuid, string $uuid, Request $request): Response - { - $locale = $this->getRequestParameter($request, 'locale', true); - $document = $this->documentManager->find( - $uuid, - $locale, - [ - 'load_ghost_content' => true, - 'load_shadow_content' => true, - ] - ); - - if ($articleUuid !== $document->getParent()->getUuid()) { - // it is required that the parent will be called to resolve the proxy. - // this wont be done in the serialization process. - - throw new ArticlePageNotFoundException($uuid, $articleUuid); - } - - $context = new Context(); - $context->setSerializeNull(true); - $context->setGroups(['defaultPage', 'defaultArticlePage', 'smallArticle']); - - return $this->handleView( - $this->view($document)->setContext($context) - ); - } - - /** - * Create article-page. - */ - public function postAction(string $articleUuid, Request $request): Response - { - $action = $request->get('action'); - $document = $this->documentManager->create(self::DOCUMENT_TYPE); - - $locale = $this->getRequestParameter($request, 'locale', true); - $data = $request->request->all(); - - $this->persistDocument($data, $document, $locale, $articleUuid); - $this->handleActionParameter($action, $document->getParent(), $locale); - $this->documentManager->flush(); - - $context = new Context(); - $context->setSerializeNull(true); - $context->setGroups(['defaultPage', 'defaultArticlePage', 'smallArticle']); - - return $this->handleView( - $this->view($document)->setContext($context) - ); - } - - /** - * Update article-page. - */ - public function putAction(string $articleUuid, string $uuid, Request $request): Response - { - $locale = $this->getRequestParameter($request, 'locale', true); - $action = $request->get('action'); - $data = $request->request->all(); - - $document = $this->documentManager->find( - $uuid, - $locale, - [ - 'load_ghost_content' => false, - 'load_shadow_content' => false, - ] - ); - - $this->requestHashChecker->checkHash($request, $document, $document->getUuid()); - - $this->persistDocument($data, $document, $locale, $articleUuid); - $this->handleActionParameter($action, $document->getParent(), $locale); - $this->documentManager->flush(); - - $context = new Context(); - $context->setSerializeNull(true); - $context->setGroups(['defaultPage', 'defaultArticlePage', 'smallArticle']); - - return $this->handleView( - $this->view($document)->setContext($context) - ); - } - - /** - * Delete article-page. - */ - public function deleteAction(string $articleUuid, string $uuid, Request $request): Response - { - $locale = $this->getRequestParameter($request, 'locale', true); - - $document = $this->documentManager->find($uuid, $locale); - $this->documentManager->remove($document); - $this->documentManager->flush(); - - return $this->handleView($this->view(null)); - } - - public function getSecurityContext() - { - return ArticleAdmin::SECURITY_CONTEXT; - } - - /** - * Persists the document using the given information. - * - * @throws InvalidFormException - * @throws MissingParameterException - * @throws ParameterNotAllowedException - */ - private function persistDocument(array $data, object $document, string $locale, string $articleUuid): void - { - if (\array_key_exists('title', $data)) { - throw new ParameterNotAllowedException('title', \get_class($document)); - } - - $article = $this->documentManager->find($articleUuid, $locale); - - if (!\array_key_exists('template', $data)) { - $data['template'] = $article->getStructureType(); - } - - /** @var class-string<\Symfony\Component\Form\FormTypeInterface> $formType */ - $formType = $this->metadataFactory->getMetadataForAlias('article_page')->getFormType(); - - $form = $this->formFactory->create( - $formType, - $document, - [ - // disable csrf protection, since we can't produce a token, because the form is cached on the client - 'csrf_protection' => false, - ] - ); - $form->submit($data, false); - - $document->setParent($article); - - if (!$form->isValid()) { - throw new InvalidFormException($form); - } - - $this->documentManager->persist( - $document, - $locale, - [ - 'user' => $this->getUser()->getId(), - 'clear_missing_content' => false, - 'auto_name' => false, - 'auto_rename' => false, - ] - ); - } - - /** - * Delegates actions by given actionParameter, which can be retrieved from the request. - */ - private function handleActionParameter(?string $actionParameter, object $document, string $locale): void - { - switch ($actionParameter) { - case 'publish': - $this->documentManager->publish($document, $locale); - break; - } - } -} diff --git a/Controller/VersionController.php b/Controller/VersionController.php deleted file mode 100644 index 14e34c739..000000000 --- a/Controller/VersionController.php +++ /dev/null @@ -1,198 +0,0 @@ -documentManager = $documentManager; - $this->restHelper = $restHelper; - $this->userRepository = $userRepository; - } - - /** - * Returns the versions for the article with the given UUID. - */ - public function cgetAction(Request $request, string $id): Response - { - $locale = $this->getRequestParameter($request, 'locale', true); - - $document = $this->documentManager->find($id, $request->query->get('locale')); - $versions = \array_reverse( - \array_filter( - $document->getVersions(), - function($version) use ($locale) { - /* @var Version $version */ - return $version->getLocale() === $locale; - } - ) - ); - $total = \count($versions); - - $limit = $this->restHelper->getLimit(); - - $versions = \array_slice($versions, $this->restHelper->getOffset(), $limit); - - $userIds = \array_unique( - \array_map( - function($version) { - /* @var Version $version */ - return $version->getAuthor(); - }, - $versions - ) - ); - - $users = $this->userRepository->findUsersById($userIds); - $fullNamesByIds = []; - - /** @var User $user */ - foreach ($users as $user) { - $fullNamesByIds[$user->getId()] = $user->getFullName(); - } - - $versionData = []; - /** @var Version $version */ - foreach ($versions as $version) { - $versionData[] = [ - 'id' => \str_replace('.', '_', $version->getId()), - 'locale' => $version->getLocale(), - 'author' => \array_key_exists($version->getAuthor(), $fullNamesByIds) - ? $fullNamesByIds[$version->getAuthor()] : '', - 'authored' => $version->getAuthored(), - ]; - } - - $versionCollection = new ListRepresentation( - $versionData, - 'article_versions', - $request->attributes->get('_route'), - [ - 'uuid' => $id, - 'locale' => $locale, - ], - $this->restHelper->getPage(), - $limit, - $total - ); - - return $this->handleView($this->view($versionCollection)); - } - - /** - * @Post("/articles/{id}/versions/{version}") - * - * @throws RestException - */ - public function postTriggerAction(Request $request, string $id, string $version): Response - { - $action = $this->getRequestParameter($request, 'action', true); - $locale = $this->getLocale($request); - - switch ($action) { - case 'restore': - $document = $this->documentManager->find($id, $locale); - - $this->documentManager->restore( - $document, - $locale, - \str_replace('_', '.', $version) - ); - $this->documentManager->flush(); - - $data = $this->documentManager->find($id, $locale); - $view = $this->view($data, null !== $data ? Response::HTTP_OK : Response::HTTP_NO_CONTENT); - - $context = new Context(); - $context->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage']); - $context->setSerializeNull(true); - $view->setContext($context); - - break; - default: - throw new RestException(\sprintf('Unrecognized action: "%s"', $action)); - } - - return $this->handleView($view); - } - - public function getSecurityContext() - { - return ArticleAdmin::SECURITY_CONTEXT; - } - - public function getLocale(Request $request) - { - return $this->getRequestParameter($request, 'locale', true); - } - - public function getSecuredClass(): string - { - return SecurityBehavior::class; - } - - /** - * @return mixed - */ - public function getSecuredObjectId(Request $request) - { - return $request->get('uuid'); - } -} diff --git a/Controller/WebsiteArticleController.php b/Controller/WebsiteArticleController.php deleted file mode 100644 index fa545ce53..000000000 --- a/Controller/WebsiteArticleController.php +++ /dev/null @@ -1,228 +0,0 @@ -renderArticle($request, $object, $view, $pageNumber, $preview, $partial); - } - - /** - * Render article with given view. - */ - protected function renderArticle( - Request $request, - ArticleInterface $object, - string $view, - int $pageNumber, - bool $preview, - bool $partial, - array $attributes = [] - ): Response { - $object = $this->normalizeArticle($object); - - $requestFormat = $request->getRequestFormat(); - $viewTemplate = $view . '.' . $requestFormat . '.twig'; - - if (!$this->container->get('twig')->getLoader()->exists($viewTemplate)) { - throw new NotAcceptableHttpException(\sprintf('Page does not exist in "%s" format.', $requestFormat)); - } - - $content = $this->resolveArticle($object, $pageNumber); - - $parameters = $this->container->get('sulu_website.resolver.parameter')->resolve( - [], - $this->container->get('sulu_core.webspace.request_analyzer'), - null, - $preview - ); - $data = \array_merge($parameters, $content, $attributes); - - try { - if ($partial) { - $response = $this->createResponse($request); - $response->setContent( - $this->renderBlockView( - $viewTemplate, - 'content', - $data - ) - ); - - return $response; - } elseif ($preview) { - $parameters = [ - 'previewParentTemplate' => $viewTemplate, - 'previewContentReplacer' => Preview::CONTENT_REPLACER, - ]; - - return $this->render( - '@SuluWebsite/Preview/preview.html.twig', - \array_merge($data, $parameters), - $this->createResponse($request) - ); - } else { - return $this->render( - $viewTemplate, - $data, - $this->createResponse($request) - ); - } - } catch (\InvalidArgumentException $exception) { - // template not found - throw new HttpException(406, 'Error encountered when rendering content', $exception); - } - } - - /** - * Returns all the times the article-document. - * This is necessary because the preview system passes an article-page here. - */ - protected function normalizeArticle(ArticleInterface $object): ArticleDocument - { - if ($object instanceof ArticlePageDocument) { - return $object->getParent(); - } - - return $object; - } - - /** - * Serialize given article with page-number. - */ - protected function resolveArticle(ArticleInterface $object, int $pageNumber): array - { - $articleContentResolver = $this->getArticleContentResolver(); - - return $articleContentResolver->resolve($object, $pageNumber); - } - - /** - * Create response. - */ - private function createResponse(Request $request): Response - { - $response = new Response(); - $cacheLifetime = $request->attributes->get('_cacheLifetime'); - - if ($cacheLifetime) { - $response->setPublic(); - $response->headers->set( - SuluHttpCache::HEADER_REVERSE_PROXY_TTL, - $cacheLifetime - ); - $response->setMaxAge($this->getParameter('sulu_http_cache.cache.max_age')); - $response->setSharedMaxAge($this->getParameter('sulu_http_cache.cache.shared_max_age')); - } - - // we need to set the content type ourselves here - // else symfony will use the accept header of the client and the page could be cached with false content-type - // see following symfony issue: https://github.com/symfony/symfony/issues/35694 - $mimeType = $request->getMimeType($request->getRequestFormat()); - - if ($mimeType) { - $response->headers->set('Content-Type', $mimeType); - } - - return $response; - } - - /** - * @param array $parameters - */ - protected function renderBlockView(string $view, string $block, array $parameters = []): string - { - $twig = $this->getTwig(); - - $parameters = $twig->mergeGlobals($parameters); - $template = $twig->load($view); - - $level = \ob_get_level(); - \ob_start(); - - try { - $rendered = $template->renderBlock($block, $parameters); - \ob_end_clean(); - - return $rendered; - } catch (\Exception $e) { - while (\ob_get_level() > $level) { - \ob_end_clean(); - } - - throw $e; - } - } - - protected function getTwig(): Environment - { - return $this->container->get('twig'); - } - - /** - * @deprecated - */ - protected function getTemplateAttributeResolver(): TemplateAttributeResolverInterface - { - @\trigger_error(__METHOD__ . '() is deprecated since version 2.2 and will be removed in 3.0. If you need the service, you can inject it by yourself instead.', \E_USER_DEPRECATED); - - return $this->container->get('sulu_website.resolver.template_attribute'); - } - - protected function getArticleContentResolver(): ArticleContentResolverInterface - { - return $this->container->get('sulu_article.article_content_resolver'); - } - - public static function getSubscribedServices(): array - { - $subscribedServices = parent::getSubscribedServices(); - - $subscribedServices['twig'] = Environment::class; - $subscribedServices['sulu_website.resolver.template_attribute'] = TemplateAttributeResolverInterface::class; - $subscribedServices['sulu_article.article_content_resolver'] = ArticleContentResolverInterface::class; - $subscribedServices['sulu_website.resolver.parameter'] = ParameterResolverInterface::class; - $subscribedServices['sulu_core.webspace.request_analyzer'] = RequestAnalyzerInterface::class; - - return $subscribedServices; - } -} diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php deleted file mode 100644 index 7aeba3025..000000000 --- a/DependencyInjection/Configuration.php +++ /dev/null @@ -1,107 +0,0 @@ -getRootNode(); - - $rootNode - ->children() - ->scalarNode('index_name')->end() - ->arrayNode('hosts') - ->prototype('scalar')->end() - ->end() - ->arrayNode('default_main_webspace') - ->useAttributeAsKey('locale') - ->beforeNormalization() - ->ifString() - ->then(function($v) { - return ['default' => $v]; - }) - ->end() - ->prototype('scalar')->end() - ->end() - ->arrayNode('default_additional_webspaces') - ->beforeNormalization() - ->ifTrue(function($v) { - return \count(\array_filter(\array_keys($v), 'is_string')) <= 0; - }) - ->then(function($v) { - return ['default' => $v]; - }) - ->end() - ->prototype('array')->useAttributeAsKey('locale')->prototype('scalar')->end()->end() - ->defaultValue([]) - ->end() - ->arrayNode('smart_content') - ->addDefaultsIfNotSet() - ->children() - ->integerNode('default_limit')->defaultValue(100)->end() - ->end() - ->end() - ->arrayNode('documents') - ->addDefaultsIfNotSet() - ->children() - ->arrayNode('article') - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('view')->defaultValue(ArticleViewDocument::class)->end() - ->end() - ->end() - ->arrayNode('article_page') - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('view')->defaultValue(ArticlePageViewObject::class)->end() - ->end() - ->end() - ->end() - ->end() - ->arrayNode('types') - ->useAttributeAsKey('name') - ->normalizeKeys(false) - ->prototype('array') - ->children() - ->scalarNode('translation_key')->end() - ->end() - ->end() - ->end() - ->scalarNode('display_tab_all')->defaultTrue()->info('Display tab \'all\' in list view')->end() - ->scalarNode('default_author')->defaultTrue()->info('Set default author if none isset')->end() - ->arrayNode('search_fields') - ->prototype('scalar')->end()->defaultValue([ - 'title', - 'excerpt.title', - 'excerpt.description', - 'excerpt.seo.title', - 'excerpt.seo.description', - 'excerpt.seo.keywords', - 'teaser_description', - ]) - ->end() - ->end(); - - return $treeBuilder; - } -} diff --git a/DependencyInjection/ConverterCompilerPass.php b/DependencyInjection/ConverterCompilerPass.php deleted file mode 100644 index d85c3c6b7..000000000 --- a/DependencyInjection/ConverterCompilerPass.php +++ /dev/null @@ -1,36 +0,0 @@ -hasDefinition(self::SERVICE_ID)) { - return; - } - - $definition = $container->getDefinition(self::SERVICE_ID); - $definition->setClass(EventAwareConverter::class); - $definition->addArgument(new Reference('event_dispatcher')); - } -} diff --git a/DependencyInjection/DefaultArticleTypeNotFoundException.php b/DependencyInjection/DefaultArticleTypeNotFoundException.php deleted file mode 100644 index 7a4d8ece6..000000000 --- a/DependencyInjection/DefaultArticleTypeNotFoundException.php +++ /dev/null @@ -1,52 +0,0 @@ -structureType = $structureType; - $this->type = $type; - } - - /** - * Returns type. - */ - public function getType(): string - { - return $this->type; - } - - /** - * Returns structure-type. - */ - public function getStructureType(): string - { - return $this->structureType; - } -} diff --git a/DependencyInjection/RouteEnhancerCompilerPass.php b/DependencyInjection/RouteEnhancerCompilerPass.php deleted file mode 100644 index 1f9855c75..000000000 --- a/DependencyInjection/RouteEnhancerCompilerPass.php +++ /dev/null @@ -1,29 +0,0 @@ -hasDefinition('sulu_route.routing.router')) { - return; - } - - $router = $container->getDefinition('sulu_route.routing.router'); - $router->addMethodCall('addRouteEnhancer', [new Reference('sulu_article.route_enhancer'), 100]); - } -} diff --git a/DependencyInjection/StructureValidatorCompilerPass.php b/DependencyInjection/StructureValidatorCompilerPass.php deleted file mode 100644 index b645d4e08..000000000 --- a/DependencyInjection/StructureValidatorCompilerPass.php +++ /dev/null @@ -1,45 +0,0 @@ -getParameter('sulu.content.structure.default_types'); - /** @var StructureMetadataFactory $structureFactory */ - $structureFactory = $container->get('sulu_page.structure.factory'); - - foreach ($types as $type) { - $defaultType = $defaultTypes[$type] ?? null; - - if (!$defaultType) { - continue; - } - - try { - $structureFactory->getStructureMetadata($type, $defaultType); - } catch (StructureTypeNotFoundException $exception) { - throw new DefaultArticleTypeNotFoundException($type, $defaultType, $exception); - } - } - } -} diff --git a/DependencyInjection/SuluArticleExtension.php b/DependencyInjection/SuluArticleExtension.php deleted file mode 100644 index fee6c318b..000000000 --- a/DependencyInjection/SuluArticleExtension.php +++ /dev/null @@ -1,426 +0,0 @@ -getExtensionConfig($this->getAlias()); - $resolvingBag = $container->getParameterBag(); - $configs = $resolvingBag->resolveValue($configs); - $config = $this->processConfiguration(new Configuration(), $configs); - - if ($container->hasExtension('jms_serializer')) { - $container->prependExtensionConfig( - 'jms_serializer', - [ - 'metadata' => [ - 'directories' => [ - 'sulu_article' => [ - 'path' => __DIR__ . '/../Resources/config/serializer', - 'namespace_prefix' => 'Sulu\Bundle\ArticleBundle', - ], - ], - ], - ] - ); - } - if ($container->hasExtension('sulu_admin')) { - $container->prependExtensionConfig( - 'sulu_admin', - [ - 'lists' => [ - 'directories' => [ - __DIR__ . '/../Resources/config/lists', - ], - ], - 'forms' => [ - 'directories' => [ - \class_exists(LocalizedLastModifiedBehavior::class) - ? __DIR__ . '/../Resources/config/forms' - : __DIR__ . '/../Resources/config/forms_sulu_25_or_lower', - ], - ], - 'resources' => [ - 'articles' => [ - 'routes' => [ - 'list' => 'sulu_article.get_articles', - 'detail' => 'sulu_article.get_article', - ], - ], - 'article_versions' => [ - 'routes' => [ - 'list' => 'sulu_article.get_article_versions', - 'detail' => 'sulu_article.post_article_version_trigger', - ], - ], - ], - 'field_type_options' => [ - 'selection' => [ - 'article_selection' => [ - 'default_type' => 'list_overlay', - 'resource_key' => 'articles', - 'types' => [ - 'list_overlay' => [ - 'adapter' => 'table', - 'list_key' => 'articles', - 'display_properties' => ['title', 'routePath'], - 'icon' => 'su-newspaper', - 'label' => 'sulu_article.selection_label', - 'overlay_title' => 'sulu_article.selection_overlay_title', - ], - ], - ], - ], - 'single_selection' => [ - 'single_article_selection' => [ - 'default_type' => 'list_overlay', - 'resource_key' => 'articles', - 'types' => [ - 'list_overlay' => [ - 'adapter' => 'table', - 'list_key' => 'articles', - 'display_properties' => ['title'], - 'empty_text' => 'sulu_article.no_article_selected', - 'icon' => 'su-newspaper', - 'overlay_title' => 'sulu_article.single_selection_overlay_title', - ], - ], - ], - ], - ], - ] - ); - } - - if ($container->hasExtension('sulu_core')) { - // can be removed when phpcr storage is removed - $container->prependExtensionConfig( - 'sulu_core', - [ - 'content' => [ - 'structure' => [ - 'paths' => [ - 'article' => [ - 'path' => '%kernel.project_dir%/config/templates/articles', - 'type' => 'article', - ], - 'article_page' => [ - 'path' => '%kernel.project_dir%/config/templates/articles', - 'type' => 'article_page', - ], - ], - 'type_map' => [ - 'article' => ArticleBridge::class, - 'article_page' => ArticlePageBridge::class, - ], - ], - ], - ] - ); - } - - if ($container->hasExtension('sulu_route')) { - // can be removed when phpcr storage is removed - $container->prependExtensionConfig( - 'sulu_route', - [ - 'mappings' => [ - 'Sulu\Bundle\ArticleBundle\Document\ArticleDocument' => [ - 'resource_key' => 'articles', - ], - 'Sulu\Bundle\ArticleBundle\Document\ArticlePageDocument' => [ - 'resource_key' => 'article_pages', - ], - ], - ] - ); - } - - if ($container->hasExtension('sulu_search')) { - // can be removed when phpcr storage is removed - $container->prependExtensionConfig( - 'sulu_page', - [ - 'search' => [ - 'mapping' => [ - ArticleDocument::class => ['index' => 'article', 'decorate_index' => true], - ArticlePageDocument::class => ['index' => 'article_page'], - ], - ], - ] - ); - } - - if ($container->hasExtension('sulu_document_manager')) { - // can be removed when phpcr storage is removed - $container->prependExtensionConfig( - 'sulu_document_manager', - [ - 'mapping' => [ - 'article' => [ - 'class' => ArticleDocument::class, - 'phpcr_type' => 'sulu:article', - 'form_type' => ArticleDocumentType::class, - ], - 'article_page' => [ - 'class' => ArticlePageDocument::class, - 'phpcr_type' => 'sulu:articlepage', - 'form_type' => ArticlePageDocumentType::class, - ], - ], - 'path_segments' => [ - 'articles' => 'articles', - ], - ] - ); - } - - if ($container->hasExtension('fos_js_routing')) { - // can be removed when phpcr storage is removed - $container->prependExtensionConfig( - 'fos_js_routing', - [ - 'routes_to_expose' => [ - 'sulu_article.post_article_version_trigger', - ], - ] - ); - } - - if ($container->hasExtension('fos_rest')) { - // can be removed when phpcr storage is removed - $container->prependExtensionConfig( - 'fos_rest', - [ - 'exception' => [ - 'codes' => [ - ParameterNotAllowedException::class => 400, - ArticlePageNotFoundException::class => 404, - ], - ], - ] - ); - } - - if ($container->hasExtension('massive_build')) { - // can be removed when phpcr storage is removed - $container->prependExtensionConfig( - 'massive_build', - [ - 'targets' => [ - 'prod' => [ - 'dependencies' => [ - 'article_index' => [], - ], - ], - 'dev' => [ - 'dependencies' => [ - 'article_index' => [], - ], - ], - 'maintain' => [ - 'dependencies' => [ - 'article_index' => [], - ], - ], - ], - ] - ); - } - - if ($container->hasExtension('ongr_elasticsearch')) { - // can be removed when phpcr storage is removed - $configs = $container->getExtensionConfig($this->getAlias()); - $config = $this->processConfiguration(new Configuration(), $configs); - - $indexName = $config['index_name']; - $hosts = $config['hosts']; - - $ongrElasticSearchConfig = [ - 'managers' => [ - 'default' => [ - 'index' => [ - 'index_name' => $indexName, - ], - 'mappings' => ['SuluArticleBundle'], - ], - 'live' => [ - 'index' => [ - 'index_name' => $indexName . '_live', - ], - 'mappings' => ['SuluArticleBundle'], - ], - ], - ]; - - if (\count($hosts) > 0) { - $ongrElasticSearchConfig['managers']['default']['index']['hosts'] = $hosts; - $ongrElasticSearchConfig['managers']['live']['index']['hosts'] = $hosts; - } - - $container->prependExtensionConfig( - 'ongr_elasticsearch', - $ongrElasticSearchConfig - ); - } - } - - /** - * @param mixed[] $configs - */ - public function load(array $configs, ContainerBuilder $container) - { - $configuration = new Configuration(); - /** - * @var array{ - * storage: 'experimental'|'phpcr', - * objects: array, - * default_main_webspace: string|null, - * default_additional_webspaces: string[]|null, - * types: array, - * display_tab_all: bool, - * smart_content: array{ - * default_limit: int, - * }, - * search_fields: string[], - * documents: array, - * default_author: bool, - * } $config - */ - $config = $this->processConfiguration($configuration, $configs); - - $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); - - $storage = $config['storage']; - $container->setParameter('sulu_article.article_storage', $storage); - - $container->setParameter('sulu_article.default_main_webspace', $config['default_main_webspace']); - $container->setParameter('sulu_article.default_additional_webspaces', $config['default_additional_webspaces']); - $container->setParameter('sulu_article.types', $config['types']); - $container->setParameter('sulu_article.display_tab_all', $config['display_tab_all']); - $container->setParameter('sulu_article.smart_content.default_limit', $config['smart_content']['default_limit']); - $container->setParameter('sulu_article.search_fields', $config['search_fields']); - $container->setParameter('sulu_article.documents', $config['documents']); - $container->setParameter('sulu_article.view_document.article.class', $config['documents']['article']['view']); - - $loader->load('services.xml'); - - /** @var array $bundles */ - $bundles = $container->getParameter('kernel.bundles'); - if (\array_key_exists('SuluAutomationBundle', $bundles)) { - $loader->load('automation.xml'); - } - if (\array_key_exists('SuluTrashBundle', $bundles)) { - $loader->load('services_trash.xml'); - } - if (\array_key_exists('SuluHeadlessBundle', $bundles)) { - $loader->load('services_headless.xml'); - } - - $this->appendDefaultAuthor($config, $container); - $this->appendArticlePageConfig($container); - - $articleDocument = ArticleDocument::class; - $articlePageDocument = ArticlePageDocument::class; - - foreach ($container->getParameter('sulu_document_manager.mapping') as $mapping) { - if ('article' == $mapping['alias']) { - $articleDocument = $mapping['class']; - } - - if ('article_page' == $mapping['alias']) { - $articlePageDocument = $mapping['class']; - } - } - - $container->setParameter('sulu_article.article_document.class', $articleDocument); - $container->setParameter('sulu_article.article_page_document.class', $articlePageDocument); - } - - /** - * Append configuration for article "set_default_author". - * - * Can be removed when phpcr storage is removed. - * - * @param array{default_author: bool} $config - */ - private function appendDefaultAuthor(array $config, ContainerBuilder $container): void - { - $mapping = $container->getParameter('sulu_document_manager.mapping'); - foreach ($mapping as $key => $item) { - if ('article' === $item['alias']) { - $mapping[$key]['set_default_author'] = $config['default_author']; - } - } - - $container->setParameter('sulu_document_manager.mapping', $mapping); - $container->setParameter('sulu_article.default_author', $config['default_author']); - } - - /** - * Append configuration for article-page (cloned from article). - * - * Can be removed when phpcr storage is removed. - */ - private function appendArticlePageConfig(ContainerBuilder $container): void - { - $paths = $container->getParameter('sulu.content.structure.paths'); - $paths['article_page'] = $this->cloneArticleConfig($paths['article'], 'article_page'); - $container->setParameter('sulu.content.structure.paths', $paths); - - $defaultTypes = $container->getParameter('sulu.content.structure.default_types'); - if (isset($defaultTypes['article'])) { - $defaultTypes['article_page'] = $defaultTypes['article']; - $container->setParameter('sulu.content.structure.default_types', $defaultTypes); - } - } - - /** - * Clone given path configuration and use given type. - * - * Can be removed when phpcr storage is removed. - */ - private function cloneArticleConfig(array $config, string $type): array - { - $result = []; - foreach ($config as $item) { - $result[] = ['path' => $item['path'], 'type' => $type]; - } - - return $result; - } -} diff --git a/DependencyInjection/WebspaceSettingsConfigurationResolver.php b/DependencyInjection/WebspaceSettingsConfigurationResolver.php deleted file mode 100644 index 4d09350f5..000000000 --- a/DependencyInjection/WebspaceSettingsConfigurationResolver.php +++ /dev/null @@ -1,61 +0,0 @@ -defaultMainWebspace = $defaultMainWebspace; - $this->defaultAdditionalWebspaces = $defaultAdditionalWebspaces; - } - - public function getDefaultMainWebspaceForLocale(string $searchedLocale): string - { - if (\array_key_exists($searchedLocale, $this->defaultMainWebspace)) { - return $this->defaultMainWebspace[$searchedLocale]; - } - - if (\array_key_exists('default', $this->defaultMainWebspace)) { - return $this->defaultMainWebspace['default']; - } - - throw new InvalidConfigurationException('No configured default main webspace for locale "' . $searchedLocale . '" not found.'); - } - - public function getDefaultAdditionalWebspacesForLocale(string $searchedLocale): array - { - if (\array_key_exists($searchedLocale, $this->defaultAdditionalWebspaces)) { - return $this->defaultAdditionalWebspaces[$searchedLocale]; - } - - if (\array_key_exists('default', $this->defaultAdditionalWebspaces)) { - return $this->defaultAdditionalWebspaces['default']; - } - - return []; - } -} diff --git a/Document/ArticleDocument.php b/Document/ArticleDocument.php deleted file mode 100644 index a6658df4e..000000000 --- a/Document/ArticleDocument.php +++ /dev/null @@ -1,593 +0,0 @@ -structure = new Structure(); - $this->extensions = new ExtensionContainer(); - $this->children = new \ArrayIterator(); - } - - public function getUuid() - { - return $this->uuid; - } - - public function setUuid($uuid): RoutablePageBehavior - { - $this->uuid = $uuid; - - return $this; - } - - public function getNodeName() - { - return $this->nodeName; - } - - public function getPath() - { - return $this->path; - } - - public function getParent() - { - return $this->parent; - } - - public function setParent($document) - { - $this->parent = $document; - } - - public function getTitle() - { - return $this->title; - } - - public function setTitle($title) - { - $this->title = $title; - } - - /** - * Returns route. - * - * @return RouteInterface - */ - public function getRoute() - { - return $this->route; - } - - public function setRoute(RouteInterface $route) - { - $this->route = $route; - } - - public function removeRoute(): RoutablePageBehavior - { - $this->route = null; - $this->routePath = null; - - return $this; - } - - public function getRoutePath(): ?string - { - return $this->routePath; - } - - public function setRoutePath($routePath): RoutablePageBehavior - { - $this->routePath = $routePath; - - return $this; - } - - public function getClass(): string - { - return \get_class($this); - } - - public function getLocale() - { - return $this->locale; - } - - public function setLocale($locale) - { - $this->locale = $locale; - } - - public function getOriginalLocale() - { - return $this->originalLocale; - } - - public function setOriginalLocale($locale) - { - $this->originalLocale = $locale; - } - - public function getStructureType(): ?string - { - return $this->structureType; - } - - public function setStructureType($structureType) - { - $this->structureType = $structureType; - } - - public function getStructure(): StructureInterface - { - return $this->structure; - } - - public function getCreator() - { - return $this->creator; - } - - /** - * @param int|null $userId - * - * @return void - */ - public function setCreator($userId) - { - $this->creator = $userId; - } - - public function getChanger() - { - return $this->changer; - } - - public function getCreated() - { - return $this->created; - } - - /** - * @param \DateTime $created - * - * @return void - */ - public function setCreated($created) - { - $this->created = $created; - } - - public function getChanged() - { - return $this->changed; - } - - /** - * Returns identifier. - * - * @return mixed - */ - public function getId() - { - return $this->getUuid(); - } - - public function getExtensionsData() - { - return $this->extensions; - } - - public function setExtensionsData($extensions) - { - $this->extensions = $extensions; - } - - public function setExtension($name, $data) - { - $this->extensions[$name] = $data; - } - - public function getWorkflowStage() - { - return $this->workflowStage; - } - - public function setWorkflowStage($workflowStage) - { - $this->workflowStage = $workflowStage; - } - - public function getPublished() - { - return $this->published; - } - - public function getAuthored() - { - return $this->authored; - } - - /** - * @return bool - */ - public function getLastModifiedEnabled() - { - return null !== $this->lastModified; - } - - /** - * @param \DateTime|null $lastModified - * - * @return void - */ - public function setLastModified($lastModified) - { - $this->lastModified = $lastModified; - } - - /** - * @return \DateTime|null - */ - public function getLastModified() - { - return $this->lastModified; - } - - public function setAuthored($authored) - { - $this->authored = $authored; - } - - public function getAuthor() - { - return $this->author; - } - - public function setAuthor($author) - { - $this->author = $author; - } - - public function getVersions() - { - return $this->versions; - } - - public function setVersions($versions) - { - $this->versions = $versions; - } - - public function getChildren() - { - return $this->children; - } - - public function getArticleUuid(): string - { - return $this->getUuid(); - } - - public function getPageUuid(): string - { - return $this->getUuid(); - } - - public function getPageNumber(): int - { - return 1; - } - - public function getPageTitle(): ?string - { - return $this->pageTitle; - } - - /** - * Set pageTitle. - * - * @param string $pageTitle - * - * @return $this - */ - public function setPageTitle($pageTitle) - { - $this->pageTitle = $pageTitle; - - return $this; - } - - /** - * Returns pages. - * - * @return array - */ - public function getPages() - { - return $this->pages; - } - - /** - * Set pages. - * - * @param array $pages - * - * @return $this - */ - public function setPages($pages) - { - $this->pages = $pages; - - return $this; - } - - public function getShadowLocale() - { - return $this->shadowLocale; - } - - public function setShadowLocale($shadowLocale) - { - $this->shadowLocale = $shadowLocale; - } - - public function isShadowLocaleEnabled() - { - return $this->shadowLocaleEnabled; - } - - public function setShadowLocaleEnabled($shadowLocaleEnabled) - { - $this->shadowLocaleEnabled = $shadowLocaleEnabled; - } - - public function getMainWebspace(): ?string - { - return $this->mainWebspace; - } - - public function setMainWebspace(?string $mainWebspace): WebspaceBehavior - { - $this->mainWebspace = $mainWebspace; - - return $this; - } - - public function getAdditionalWebspaces(): ?array - { - return $this->additionalWebspaces; - } - - public function setAdditionalWebspaces(?array $additionalWebspaces): WebspaceBehavior - { - $this->additionalWebspaces = $additionalWebspaces; - - return $this; - } -} diff --git a/Document/ArticleInterface.php b/Document/ArticleInterface.php deleted file mode 100644 index 58f742ccb..000000000 --- a/Document/ArticleInterface.php +++ /dev/null @@ -1,68 +0,0 @@ -structure = new Structure(); - } - - public function getUuid() - { - return $this->uuid; - } - - public function setUuid($uuid): RoutablePageBehavior - { - $this->uuid = $uuid; - - return $this; - } - - public function getTitle() - { - return $this->title; - } - - public function setTitle($title) - { - $this->title = $title; - - return $this; - } - - /** - * Returns pageTitle. - */ - public function getPageTitle(): ?string - { - return $this->pageTitle; - } - - /** - * Set pageTitle. - * - * @param string $pageTitle - * - * @return $this - */ - public function setPageTitle($pageTitle) - { - $this->pageTitle = $pageTitle; - - return $this; - } - - public function getParent() - { - return $this->parent; - } - - public function setParent($parent) - { - $this->parent = $parent; - - return $this; - } - - public function getPath() - { - return $this->path; - } - - public function getLocale() - { - return $this->locale; - } - - public function setLocale($locale) - { - $this->locale = $locale; - - return $this; - } - - public function getOriginalLocale() - { - return $this->originalLocale; - } - - public function setOriginalLocale($originalLocale) - { - $this->originalLocale = $originalLocale; - - return $this; - } - - public function getStructureType(): ?string - { - return $this->structureType; - } - - public function setStructureType($structureType) - { - $this->structureType = $structureType; - - return $this; - } - - public function getStructure(): StructureInterface - { - return $this->structure; - } - - public function getId() - { - return $this->uuid; - } - - public function getRoute() - { - return $this->route; - } - - public function setRoute(RouteInterface $route) - { - $this->route = $route; - - return $this; - } - - public function removeRoute(): RoutablePageBehavior - { - $this->route = null; - $this->routePath = null; - - return $this; - } - - public function getRoutePath(): ?string - { - return $this->routePath; - } - - public function setRoutePath($routePath): RoutablePageBehavior - { - $this->routePath = $routePath; - - return $this; - } - - public function getClass(): string - { - return \get_class($this); - } - - public function getPageNumber(): int - { - return $this->pageNumber; - } - - public function setPageNumber(int $pageNumber): PageBehavior - { - $this->pageNumber = $pageNumber; - - return $this; - } - - public function getArticleUuid(): string - { - return $this->getParent()->getUuid(); - } - - public function getPageUuid(): string - { - return $this->getUuid(); - } - - public function getWorkflowStage() - { - return $this->getParent()->getWorkflowStage(); - } - - public function getExtensionsData() - { - return $this->getParent()->getExtensionsData(); - } - - public function getShadowLocale() - { - return $this->shadowLocale; - } - - public function setShadowLocale($shadowLocale) - { - $this->shadowLocale = $shadowLocale; - } - - public function isShadowLocaleEnabled() - { - return $this->shadowLocaleEnabled; - } - - public function setShadowLocaleEnabled($shadowLocaleEnabled) - { - $this->shadowLocaleEnabled = $shadowLocaleEnabled; - } -} diff --git a/Document/ArticlePageViewObject.php b/Document/ArticlePageViewObject.php deleted file mode 100644 index 8afab9488..000000000 --- a/Document/ArticlePageViewObject.php +++ /dev/null @@ -1,84 +0,0 @@ -uuid = $uuid; - } - - public function getId() - { - return $this->id; - } - - public function setId($id) - { - $this->id = $id; - - return $this; - } - - public function getUuid() - { - return $this->uuid; - } - - public function setUuid($uuid) - { - $this->uuid = $uuid; - - return $this; - } - - public function getLocale() - { - return $this->locale; - } - - public function setLocale($locale) - { - $this->locale = $locale; - - return $this; - } - - public function getTitle() - { - return $this->title; - } - - public function setTitle($title) - { - $this->title = $title; - - return $this; - } - - public function getRoutePath() - { - return $this->routePath; - } - - public function setRoutePath($routePath) - { - $this->routePath = $routePath; - - return $this; - } - - public function getParentPageUuid() - { - return $this->parentPageUuid; - } - - public function setParentPageUuid($parentPageUuid) - { - $this->parentPageUuid = $parentPageUuid; - - return $this; - } - - public function getType() - { - return $this->type; - } - - public function setType($type) - { - $this->type = $type; - - return $this; - } - - public function getTypeTranslation() - { - return $this->typeTranslation; - } - - public function setTypeTranslation($typeTranslation) - { - $this->typeTranslation = $typeTranslation; - - return $this; - } - - public function getStructureType() - { - return $this->structureType; - } - - public function setStructureType($structureType) - { - $this->structureType = $structureType; - - return $this; - } - - public function getChangerFullName() - { - return $this->changerFullName; - } - - public function setChangerFullName($changerFullName) - { - $this->changerFullName = $changerFullName; - - return $this; - } - - public function getCreatorFullName() - { - return $this->creatorFullName; - } - - public function setCreatorFullName($creatorFullName) - { - $this->creatorFullName = $creatorFullName; - - return $this; - } - - public function getChanged() - { - return $this->changed; - } - - public function setChanged($changed) - { - $this->changed = $changed; - - return $this; - } - - public function getCreated() - { - return $this->created; - } - - public function setCreated($created) - { - $this->created = $created; - - return $this; - } - - public function getExcerpt() - { - return $this->excerpt; - } - - public function setExcerpt(ExcerptViewObject $excerpt) - { - $this->excerpt = $excerpt; - - return $this; - } - - public function getSeo() - { - return $this->seo; - } - - public function setSeo(SeoViewObject $seo) - { - $this->seo = $seo; - - return $this; - } - - public function getLastModified() - { - return $this->lastModified; - } - - public function setLastModified($lastModified) - { - $this->lastModified = $lastModified; - $this->updateLastModifiedOrAuthored(); - - return $this; - } - - public function getLastModifiedOrAuthored(): \DateTime - { - return $this->lastModified ?? $this->authored; - } - - /** - * @internal setter is required for ONGR but should not be used - * - * @return static - */ - public function setLastModifiedOrAuthored(\DateTime $lastModifiedOrAuthored) - { - $this->lastModifiedOrAuthored = $lastModifiedOrAuthored; - - return $this; - } - - public function updateLastModifiedOrAuthored() - { - $this->lastModifiedOrAuthored = $this->lastModified ?? $this->authored; - - return $this; - } - - public function getAuthored() - { - return $this->authored; - } - - public function setAuthored(?\DateTime $authored = null) - { - $this->authored = $authored; - $this->updateLastModifiedOrAuthored(); - - return $this; - } - - public function getAuthorFullName() - { - return $this->authorFullName; - } - - public function setAuthorFullName($authorFullName) - { - $this->authorFullName = $authorFullName; - - return $this; - } - - public function getTeaserDescription() - { - return $this->teaserDescription; - } - - public function setTeaserDescription($teaserDescription) - { - $this->teaserDescription = $teaserDescription; - - return $this; - } - - public function getTeaserMediaId() - { - return $this->teaserMediaId; - } - - public function setTeaserMediaId($teaserMediaId) - { - $this->teaserMediaId = $teaserMediaId; - - return $this; - } - - public function getPublished() - { - return $this->published; - } - - public function setPublished(?\DateTime $published = null) - { - $this->published = $published; - - return $this; - } - - public function getPublishedState() - { - return $this->publishedState; - } - - public function setPublishedState($publishedState) - { - $this->publishedState = $publishedState; - - return $this; - } - - public function getLocalizationState() - { - return $this->localizationState; - } - - public function setLocalizationState(LocalizationStateViewObject $localizationState) - { - $this->localizationState = $localizationState; - - return $this; - } - - public function setAuthorId($authorId) - { - $this->authorId = $authorId; - - return $this; - } - - public function getAuthorId() - { - return $this->authorId; - } - - public function setCreatorContactId($creatorContactId) - { - $this->creatorContactId = $creatorContactId; - - return $this; - } - - public function getCreatorContactId() - { - return $this->creatorContactId; - } - - public function setChangerContactId($changerContactId) - { - $this->changerContactId = $changerContactId; - - return $this; - } - - public function getChangerContactId() - { - return $this->changerContactId; - } - - public function getPages() - { - return $this->pages; - } - - public function setPages($pages) - { - $this->pages = $pages; - - return $this; - } - - public function getContentData() - { - return $this->contentData; - } - - public function setContentData($contentData) - { - $this->contentData = $contentData; - - return $this; - } - - public function getContent() - { - return $this->content; - } - - public function setContent(\ArrayObject $content) - { - $this->content = $content; - - return $this; - } - - public function getView() - { - return $this->view; - } - - public function setView(\ArrayObject $view) - { - $this->view = $view; - - return $this; - } - - public function getMainWebspace() - { - return $this->mainWebspace; - } - - public function setMainWebspace($mainWebspace) - { - $this->mainWebspace = $mainWebspace; - - return $this; - } - - public function getAdditionalWebspaces() - { - return $this->additionalWebspaces; - } - - public function setAdditionalWebspaces($additionalWebspace) - { - $this->additionalWebspaces = $additionalWebspace; - - return $this; - } - - public function getTargetWebspace() - { - return $this->targetWebspace; - } - - public function setTargetWebspace($targetWebspace) - { - $this->targetWebspace = $targetWebspace; - - return $this; - } - - public function getContentFields(): array - { - return $this->contentFields; - } - - public function setContentFields(array $contentFields): ArticleViewDocumentInterface - { - $this->contentFields = $contentFields; - - return $this; - } -} diff --git a/Document/ArticleViewDocumentInterface.php b/Document/ArticleViewDocumentInterface.php deleted file mode 100644 index 21df42a9b..000000000 --- a/Document/ArticleViewDocumentInterface.php +++ /dev/null @@ -1,547 +0,0 @@ -tags = new Collection(); - $this->categories = new Collection(); - $this->segments = new Collection(); - $this->icon = new Collection(); - $this->images = new Collection(); - } -} diff --git a/Document/Form/ArticleDocumentType.php b/Document/Form/ArticleDocumentType.php deleted file mode 100644 index 4e68a8bab..000000000 --- a/Document/Form/ArticleDocumentType.php +++ /dev/null @@ -1,76 +0,0 @@ -add('extensions', UnstructuredType::class, ['property_path' => 'extensionsData']); - $builder->add('shadowLocaleEnabled', CheckboxType::class); - $builder->add('shadowLocale', TextType::class); - $builder->add('mainWebspace', TextType::class); - $builder->add('additionalWebspaces', CollectionType::class, - [ - 'entry_type' => TextType::class, - 'entry_options' => [ - 'required' => false, - ], - 'allow_add' => true, - 'allow_delete' => true, - ] - ); - - $builder->add( - 'lastModified', - DateTimeType::class, - [ - 'widget' => 'single_text', - ] - ); - $builder->add('author', TextType::class); - $builder->add( - 'authored', - DateTimeType::class, - [ - 'widget' => 'single_text', - ] - ); - - $builder->addEventListener(FormEvents::PRE_SUBMIT, [DataNormalizer::class, 'normalize']); - } - - public function configureOptions(OptionsResolver $resolver) - { - $resolver->setDefaults( - [ - 'allow_extra_fields' => true, - ] - ); - } -} diff --git a/Document/Form/ArticlePageDocumentType.php b/Document/Form/ArticlePageDocumentType.php deleted file mode 100644 index 859472460..000000000 --- a/Document/Form/ArticlePageDocumentType.php +++ /dev/null @@ -1,41 +0,0 @@ -add('shadowLocaleEnabled', CheckboxType::class); - $builder->add('shadowLocale', TextType::class); - } - - public function configureOptions(OptionsResolver $resolver) - { - $resolver->setDefaults( - [ - 'allow_extra_fields' => true, - ] - ); - } -} diff --git a/Document/Form/Listener/DataNormalizer.php b/Document/Form/Listener/DataNormalizer.php deleted file mode 100644 index 1a9b71ddc..000000000 --- a/Document/Form/Listener/DataNormalizer.php +++ /dev/null @@ -1,53 +0,0 @@ -getData(); - $data = \array_merge( - [ - 'mainWebspace' => self::getAndUnsetValue($data['structure'], 'mainWebspace'), - 'additionalWebspaces' => self::getAndUnsetValue($data['structure'], 'additionalWebspaces'), - ], - $data - ); - - $event->setData($data); - } - - /** - * @return mixed|null - */ - private static function getAndUnsetValue(array &$data, string $key) - { - $value = null; - - if (isset($data[$key])) { - $value = $data[$key]; - unset($data[$key]); - } - - return $value; - } -} diff --git a/Document/Form/UnstructuredType.php b/Document/Form/UnstructuredType.php deleted file mode 100644 index b2c89b7c0..000000000 --- a/Document/Form/UnstructuredType.php +++ /dev/null @@ -1,29 +0,0 @@ -setDefaults([ - 'compound' => false, - 'multiple' => true, - ]); - } -} diff --git a/Document/Index/ArticleGhostIndexer.php b/Document/Index/ArticleGhostIndexer.php deleted file mode 100644 index 8c529593d..000000000 --- a/Document/Index/ArticleGhostIndexer.php +++ /dev/null @@ -1,132 +0,0 @@ -webspaceManager = $webspaceManager; - $this->documentManager = $documentManager; - } - - public function index(ArticleDocument $document): void - { - if ($document->isShadowLocaleEnabled()) { - $this->indexShadow($document); - - return; - } - - $article = $this->createOrUpdateArticle($document, $document->getLocale()); - $this->updateShadows($document); - $this->createOrUpdateGhosts($document); - $this->dispatchIndexEvent($document, $article); - $this->manager->persist($article); - } - - private function createOrUpdateGhosts(ArticleDocument $document): void - { - $documentLocale = $document->getLocale(); - /** @var Localization $localization */ - foreach ($this->webspaceManager->getAllLocalizations() as $localization) { - $locale = $localization->getLocale(); - if ($documentLocale === $locale) { - continue; - } - - /** @var ArticleDocument $ghostDocument */ - $ghostDocument = $this->documentManager->find( - $document->getUuid(), - $locale - ); - - $localizationState = $this->inspector->getLocalizationState($ghostDocument); - - // Only index ghosts - if (LocalizationState::GHOST !== $localizationState) { - continue; - } - - // Try index the article ghosts. - $article = $this->createOrUpdateArticle( - $ghostDocument, - $localization->getLocale(), - LocalizationState::GHOST - ); - - if ($article) { - $this->dispatchIndexEvent($ghostDocument, $article); - $this->manager->persist($article); - } - } - } -} diff --git a/Document/Index/ArticleIndexer.php b/Document/Index/ArticleIndexer.php deleted file mode 100644 index fd7492a16..000000000 --- a/Document/Index/ArticleIndexer.php +++ /dev/null @@ -1,595 +0,0 @@ -structureMetadataFactory = $structureMetadataFactory; - $this->userManager = $userManager; - $this->contactRepository = $contactRepository; - $this->documentFactory = $documentFactory; - $this->manager = $manager; - $this->excerptFactory = $excerptFactory; - $this->seoFactory = $seoFactory; - $this->eventDispatcher = $eventDispatcher; - $this->translator = $translator; - $this->documentManager = $documentManager; - $this->inspector = $inspector; - $this->webspaceResolver = $webspaceResolver; - $this->typeConfiguration = $typeConfiguration; - } - - /** - * Returns translation for given article type. - */ - private function getTypeTranslation(string $type): string - { - if (!\array_key_exists($type, $this->typeConfiguration)) { - return \ucfirst($type); - } - - $typeTranslationKey = $this->typeConfiguration[$type]['translation_key']; - - return $this->translator->trans($typeTranslationKey, [], 'admin'); - } - - protected function dispatchIndexEvent(ArticleDocument $document, ArticleViewDocumentInterface $article): void - { - $this->eventDispatcher->dispatch(new IndexEvent($document, $article), IndexEvent::NAME); - } - - protected function createOrUpdateArticle( - ArticleDocument $document, - string $locale, - string $localizationState = LocalizationState::LOCALIZED - ): ?ArticleViewDocumentInterface { - $article = $this->findOrCreateViewDocument($document, $locale, $localizationState); - if (!$article) { - return null; - } - - $structureMetadata = $this->structureMetadataFactory->getStructureMetadata( - 'article', - $document->getStructureType() - ); - - $article->setTitle($document->getTitle()); - $article->setRoutePath($document->getRoutePath()); - $this->setParentPageUuid($document, $article); - $article->setChanged($document->getChanged()); - $article->setCreated($document->getCreated()); - $article->setLastModified($document->getLastModified()); - $article->setAuthored($document->getAuthored()); - if ($document->getAuthor() && $author = $this->contactRepository->find($document->getAuthor())) { - $article->setAuthorId($author->getId()); - - if ($author instanceof Contact) { - $article->setAuthorFullName($author->getFullName()); - } - } - if ($document->getChanger() && $changer = $this->userManager->getUserById($document->getChanger())) { - $article->setChangerFullName($changer->getFullName()); - - if ($changer instanceof User) { - $article->setChangerContactId($changer->getContact()->getId()); - } - } - if ($document->getCreator() && $creator = $this->userManager->getUserById($document->getCreator())) { - $article->setCreatorFullName($creator->getFullName()); - - if ($creator instanceof User) { - $article->setCreatorContactId($creator->getContact()->getId()); - } - } - $article->setType($this->getType($structureMetadata)); - $article->setStructureType($document->getStructureType()); - $article->setPublished($document->getPublished()); - $article->setPublishedState(WorkflowStage::PUBLISHED === $document->getWorkflowStage()); - $article->setTypeTranslation($this->getTypeTranslation($this->getType($structureMetadata))); - $article->setLocalizationState( - new LocalizationStateViewObject( - $localizationState, - (LocalizationState::LOCALIZED === $localizationState) ? null : $document->getLocale() - ) - ); - - $extensions = $document->getExtensionsData(); - - if ($extensions instanceof ExtensionContainer) { - $extensions = $extensions->toArray(); - } - - if (\array_key_exists('excerpt', $extensions)) { - $article->setExcerpt($this->excerptFactory->create($extensions['excerpt'], $document->getLocale())); - } - if (\array_key_exists('seo', $extensions)) { - $article->setSeo($this->seoFactory->create($extensions['seo'])); - } - if ($structureMetadata->hasPropertyWithTagName('sulu.teaser.description')) { - $descriptionProperty = $structureMetadata->getPropertyByTagName('sulu.teaser.description'); - $article->setTeaserDescription( - $document->getStructure()->getProperty($descriptionProperty->getName())->getValue() - ); - } - if ($structureMetadata->hasPropertyWithTagName('sulu.teaser.media')) { - $mediaProperty = $structureMetadata->getPropertyByTagName('sulu.teaser.media'); - $mediaData = $document->getStructure()->getProperty($mediaProperty->getName())->getValue(); - if (null !== $mediaData && \array_key_exists('ids', $mediaData)) { - $article->setTeaserMediaId(\reset($mediaData['ids']) ?: null); - } - } - - $article->setContentFields($this->getContentFields($structureMetadata, $document)); - $article->setContentData(\json_encode($document->getStructure()->toArray())); - - $article->setMainWebspace($this->webspaceResolver->resolveMainWebspace($document)); - $article->setAdditionalWebspaces($this->webspaceResolver->resolveAdditionalWebspaces($document)); - - $this->mapPages($document, $article); - - return $article; - } - - protected function getContentFields(StructureMetadata $structure, ArticleDocument $document) - { - $tag = 'sulu.search.field'; - $contentFields = []; - foreach ($structure->getProperties() as $property) { - if (\method_exists($property, 'getComponents') && \count($property->getComponents()) > 0) { - $blocks = $document->getStructure()->getProperty($property->getName())->getValue(); - if (isset($blocks['hotspots'])) { - $blocks = $blocks['hotspots']; - } - $contentFields = \array_merge($contentFields, $this->getBlockContentFieldsRecursive($blocks, $document, $property, $tag)); - } elseif ($property->hasTag($tag)) { - $value = $document->getStructure()->getProperty($property->getName())->getValue(); - if (\is_string($value) && '' !== $value) { - $contentFields[] = \strip_tags($value); - } - } - } - - return $contentFields; - } - - /** - * @return string[] - */ - private function getBlockContentFieldsRecursive(array $blocks, ArticleDocument $document, $blockMetaData, $tag) - { - $contentFields = []; - foreach ($blockMetaData->getComponents() as $component) { - /** @var PropertyMetadata $componentProperty */ - foreach ($component->getChildren() as $componentProperty) { - if (\method_exists($componentProperty, 'getComponents') && \count($componentProperty->getComponents()) > 0) { - $filteredBlocks = \array_filter($blocks, function($block) use ($component) { - return $block['type'] === $component->getName(); - }); - - foreach ($filteredBlocks as $filteredBlock) { - if (isset($filteredBlock['hotspots'])) { - $filteredBlock = $filteredBlock['hotspots']; - } - $contentFields = \array_merge( - $contentFields, - $this->getBlockContentFieldsRecursive( - $filteredBlock[$componentProperty->getName()], - $document, - $componentProperty, - $tag - ) - ); - } - } - - if (false === $componentProperty->hasTag($tag)) { - continue; - } - - foreach ($blocks as $block) { - if ($block['type'] === $component->getName()) { - $blockValue = $block[$componentProperty->getName()]; - if (\is_string($blockValue) && '' !== $blockValue) { - $contentFields[] = \strip_tags($blockValue); - } - } - } - } - } - - return $contentFields; - } - - protected function findViewDocument(ArticleDocument $document, string $locale): ?ArticleViewDocumentInterface - { - $articleId = $this->getViewDocumentId($document->getUuid(), $locale); - /** @var ArticleViewDocumentInterface $article */ - $article = $this->manager->find($this->documentFactory->getClass('article'), $articleId); - - return $article; - } - - /** - * Returns view-document from index or create a new one. - */ - protected function findOrCreateViewDocument( - ArticleDocument $document, - string $locale, - string $localizationState - ): ?ArticleViewDocumentInterface { - $article = $this->findViewDocument($document, $locale); - - if ($article) { - // Only index ghosts when the article isn't a ghost himself. - if (LocalizationState::GHOST === $localizationState - && LocalizationState::GHOST !== $article->getLocalizationState()->state - ) { - return null; - } - - return $article; - } - - $article = $this->documentFactory->create('article'); - $article->setId($this->getViewDocumentId($document->getUuid(), $locale)); - $article->setUuid($document->getUuid()); - $article->setLocale($locale); - - return $article; - } - - /** - * Maps pages from document to view-document. - */ - private function mapPages(ArticleDocument $document, ArticleViewDocumentInterface $article): void - { - $pages = []; - /** @var ArticlePageDocument $child */ - foreach ($document->getChildren() as $child) { - if (!$child instanceof ArticlePageDocument) { - continue; - } - - /** @var ArticlePageViewObject $page */ - $page = $this->documentFactory->create('article_page'); - $page->uuid = $child->getUuid(); - $page->pageNumber = $child->getPageNumber(); - $page->title = $child->getPageTitle(); - $page->routePath = $child->getRoutePath(); - $page->contentData = \json_encode($child->getStructure()->toArray()); - - $pages[] = $page; - } - - $article->setPages(new Collection($pages)); - } - - /** - * Set parent-page-uuid to view-document. - */ - private function setParentPageUuid(ArticleDocument $document, ArticleViewDocumentInterface $article): void - { - $parentPageUuid = $this->getParentPageUuidFromPageTree($document); - - if (!$parentPageUuid) { - return; - } - - $article->setParentPageUuid($parentPageUuid); - } - - protected function removeArticle(string $id): void - { - $article = $this->manager->find( - $this->documentFactory->getClass('article'), - $id - ); - if (null === $article) { - return; - } - - $this->manager->remove($article); - } - - public function remove(ArticleDocument $document/*, ?string $locale = null*/): void - { - $locale = \func_num_args() >= 2 ? \func_get_arg(1) : null; - - $repository = $this->manager->getRepository($this->documentFactory->getClass('article')); - $search = $repository->createSearch() - ->addQuery(new TermQuery('uuid', $document->getUuid())) - ->setSize(1000); - - if ($locale) { - $search->addQuery(new TermQuery('locale', $locale)); - } - - foreach ($repository->findDocuments($search) as $viewDocument) { - $this->manager->remove($viewDocument); - } - } - - /** - * @deprecated - * @see ArticleIndexer::replaceWithGhostData - */ - public function removeLocale(ArticleDocument $document, string $locale): void - { - @\trigger_error('Calling ArticleIndexer::removeLocale() is deprecated and will be removed in future. Use ArticleIndexer::replaceWithGhostData() instead.', \E_USER_DEPRECATED); - - $this->replaceWithGhostData($document, $locale); - } - - public function replaceWithGhostData(ArticleDocument $document, string $locale): void - { - // overwrite removed locale with properties from original locale - $article = $this->createOrUpdateArticle($document, $locale); - $article->setLocalizationState(new LocalizationStateViewObject(LocalizationState::GHOST, $document->getOriginalLocale())); - - $repository = $this->manager->getRepository($this->documentFactory->getClass('article')); - $search = $repository->createSearch(); - $search->addQuery(new TermQuery('localization_state.state', 'ghost'), BoolQuery::MUST); - $search->addQuery(new TermQuery('localization_state.locale', $locale), BoolQuery::MUST); - $search->addQuery(new TermQuery('locale', $locale), BoolQuery::MUST_NOT); - $search->addQuery(new TermQuery('uuid', $document->getUuid()), BoolQuery::MUST); - - /** @var array $searchResult */ - $searchResult = $repository->findArray($search); - foreach ($searchResult as $result) { - $this->replaceWithGhostData($document, $result['locale']); - } - - $this->manager->persist($article); - } - - public function flush(): void - { - $this->manager->commit(); - } - - public function clear(): void - { - $pageSize = 500; - $repository = $this->manager->getRepository($this->documentFactory->getClass('article')); - $search = $repository->createSearch() - ->addQuery(new MatchAllQuery()) - ->setSize($pageSize); - - do { - $result = $repository->findDocuments($search); - foreach ($result as $document) { - $this->manager->remove($document); - } - - $this->manager->commit(); - } while (0 !== $result->count()); - - $this->manager->clearCache(); - $this->manager->flush(); - } - - public function setUnpublished(string $uuid, string $locale): ?ArticleViewDocumentInterface - { - $articleId = $this->getViewDocumentId($uuid, $locale); - /** @var ArticleViewDocumentInterface|null $article */ - $article = $this->manager->find($this->documentFactory->getClass('article'), $articleId); - if (!$article) { - return null; - } - - $article->setPublished(null); - $article->setPublishedState(false); - - $this->manager->persist($article); - - return $article; - } - - public function index(ArticleDocument $document): void - { - if ($document->isShadowLocaleEnabled()) { - $this->indexShadow($document); - - return; - } - - $article = $this->createOrUpdateArticle($document, $document->getLocale()); - - $this->dispatchIndexEvent($document, $article); - $this->manager->persist($article); - - $this->updateShadows($document); - } - - protected function indexShadow(ArticleDocument $document): void - { - /** @var ArticleDocument $shadowDocument */ - $shadowDocument = $this->documentManager->find( - $document->getUuid(), - $document->getOriginalLocale(), - [ - 'rehydrate' => true, - ] - ); - - $article = $this->createOrUpdateArticle($shadowDocument, $document->getOriginalLocale(), LocalizationState::SHADOW); - $this->dispatchIndexEvent($shadowDocument, $article); - $this->manager->persist($article); - } - - protected function updateShadows(ArticleDocument $document): void - { - if ($document->isShadowLocaleEnabled()) { - return; - } - - foreach (\array_keys($this->inspector->getShadowLocales($document)) as $shadowLocale) { - try { - /** @var ArticleDocument $shadowDocument */ - $shadowDocument = $this->documentManager->find($document->getUuid(), $shadowLocale); - - // update shadow only if original document exists - if (!$this->findViewDocument($shadowDocument, $document->getLocale())) { - continue; - } - - $this->indexShadow($shadowDocument); - } catch (DocumentManagerException $documentManagerException) { - // @ignoreException - // do nothing - } - } - } - - public function dropIndex(): void - { - if (!$this->manager->indexExists()) { - return; - } - - $this->manager->dropIndex(); - } - - public function createIndex(): void - { - if ($this->manager->indexExists()) { - return; - } - - $this->manager->createIndex(); - } - - protected function getDocumentInspector() - { - return $this->inspector; - } -} diff --git a/Document/Index/DocumentFactory.php b/Document/Index/DocumentFactory.php deleted file mode 100644 index 8352d44da..000000000 --- a/Document/Index/DocumentFactory.php +++ /dev/null @@ -1,40 +0,0 @@ -documents = $documents; - } - - public function getClass(string $type): string - { - return $this->documents[$type]['view']; - } - - public function create(string $type) - { - $class = $this->getClass($type); - - return new $class(); - } -} diff --git a/Document/Index/DocumentFactoryInterface.php b/Document/Index/DocumentFactoryInterface.php deleted file mode 100644 index f2c67330b..000000000 --- a/Document/Index/DocumentFactoryInterface.php +++ /dev/null @@ -1,32 +0,0 @@ -categoryRepository = $categoryRepository; - } - - /** - * Create category collection. - * - * @param int[] $categoryIds - */ - public function create(array $categoryIds, string $locale): Collection - { - if (empty($categoryIds)) { - return new Collection(); - } - - // Load category with keywords - $queryBuilder = $this->categoryRepository->createQueryBuilder('category') - ->select(['category.id', 'category.key', 'translate.translation as name', 'keyword.keyword']) - ->leftJoin('category.translations', 'translate', Join::WITH, 'translate.locale = :locale') - ->setParameter('locale', $locale) - ->leftJoin('translate.keywords', 'keyword'); - - $queryBuilder->where($queryBuilder->expr()->in('category.id', $categoryIds)); - - $categories = []; - - foreach ($queryBuilder->getQuery()->getResult() as $categoryData) { - $id = (int) $categoryData['id']; - - if (!isset($categories[$id])) { - $categories[$id] = new CategoryViewObject(); - $categories[$id]->id = $id; - $categories[$id]->key = $categoryData['key']; - $categories[$id]->name = $categoryData['name']; - } - - $categories[$id]->keywords[] = $categoryData['keyword']; - } - - return new Collection(\array_values($categories)); - } -} diff --git a/Document/Index/Factory/ExcerptFactory.php b/Document/Index/Factory/ExcerptFactory.php deleted file mode 100644 index 99fbbeaf5..000000000 --- a/Document/Index/Factory/ExcerptFactory.php +++ /dev/null @@ -1,79 +0,0 @@ -categoryCollectionFactory = $categoryCollectionFactory; - $this->tagCollectionFactory = $tagCollectionFactory; - $this->mediaCollectionFactory = $mediaCollectionFactory; - $this->segmentCollectionFactory = $segmentCollectionFactory; - } - - /** - * Create a excerpt object by given data. - */ - public function create(array $data, string $locale): ExcerptViewObject - { - $excerpt = new ExcerptViewObject(); - - if (empty($data)) { - return $excerpt; - } - - $excerpt->title = $data['title']; - $excerpt->more = $data['more']; - $excerpt->description = $data['description']; - $excerpt->tags = $this->tagCollectionFactory->create($data['tags']); - $excerpt->categories = $this->categoryCollectionFactory->create($data['categories'], $locale); - $excerpt->segments = $this->segmentCollectionFactory->create($data['segments'] ?? []); - $excerpt->audienceTargetingGroups = $data['audience_targeting_groups'] ?? []; - $excerpt->icon = $this->mediaCollectionFactory->create($data['icon'] ?? [], $locale); - $excerpt->images = $this->mediaCollectionFactory->create($data['images'] ?? [], $locale); - - return $excerpt; - } -} diff --git a/Document/Index/Factory/MediaCollectionFactory.php b/Document/Index/Factory/MediaCollectionFactory.php deleted file mode 100644 index c6414821a..000000000 --- a/Document/Index/Factory/MediaCollectionFactory.php +++ /dev/null @@ -1,62 +0,0 @@ -mediaManager = $mediaManager; - } - - /** - * Create media collection object. - * - * @return MediaViewObject[]|Collection - */ - public function create(array $data, string $locale) - { - $mediaCollection = new Collection(); - - if (empty($data)) { - return $mediaCollection; - } - - if (\array_key_exists('ids', $data)) { - $medias = $this->mediaManager->getByIds($data['ids'], $locale); - - foreach ($medias as $media) { - $mediaViewObject = new MediaViewObject(); - $mediaViewObject->setData($media); - - $mediaCollection[] = $mediaViewObject; - } - } - - return $mediaCollection; - } -} diff --git a/Document/Index/Factory/MediaFactory.php b/Document/Index/Factory/MediaFactory.php deleted file mode 100644 index 49c638e5c..000000000 --- a/Document/Index/Factory/MediaFactory.php +++ /dev/null @@ -1,49 +0,0 @@ -mediaManager = $mediaManager; - } - - public function create(int $id, string $locale): MediaViewObject - { - $mediaViewObject = new MediaViewObject(); - - if (!$id) { - return $mediaViewObject; - } - - $media = $this->mediaManager->getById($id, $locale); - - $mediaViewObject->setData($media); - - return $mediaViewObject; - } -} diff --git a/Document/Index/Factory/SegmentCollectionFactory.php b/Document/Index/Factory/SegmentCollectionFactory.php deleted file mode 100644 index 6100f2510..000000000 --- a/Document/Index/Factory/SegmentCollectionFactory.php +++ /dev/null @@ -1,37 +0,0 @@ - $segmentKey) { - if ($segmentKey) { - $segment = new SegmentViewObject(); - $segment->assignmentKey = $webspaceKey . SegmentSelect::SEPARATOR . $segmentKey; - $segment->webspaceKey = $webspaceKey; - $segment->segmentKey = $segmentKey; - - $collection[] = $segment; - } - } - - return $collection; - } -} diff --git a/Document/Index/Factory/SeoFactory.php b/Document/Index/Factory/SeoFactory.php deleted file mode 100644 index d69364e20..000000000 --- a/Document/Index/Factory/SeoFactory.php +++ /dev/null @@ -1,42 +0,0 @@ -title = $data['title']; - $seo->description = $data['description']; - $seo->keywords = $data['keywords']; - $seo->canonicalUrl = $data['canonicalUrl']; - $seo->noIndex = $data['noIndex']; - $seo->noFollow = $data['noFollow']; - $seo->hideInSitemap = $data['hideInSitemap']; - - return $seo; - } -} diff --git a/Document/Index/Factory/TagCollectionFactory.php b/Document/Index/Factory/TagCollectionFactory.php deleted file mode 100644 index 098a93736..000000000 --- a/Document/Index/Factory/TagCollectionFactory.php +++ /dev/null @@ -1,61 +0,0 @@ -tagManager = $tagManager; - } - - /** - * Create tag collection. - * - * @param string[] $tagNames - */ - public function create(array $tagNames): Collection - { - $collection = new Collection(); - - foreach ($tagNames as $tagName) { - $tagEntity = $this->tagManager->findByName($tagName); - - if (!$tagEntity) { - return null; - } - - $tag = new TagViewObject(); - $tag->name = $tagName; - $tag->id = $tagEntity->getId(); - - $collection[] = $tag; - } - - return $collection; - } -} diff --git a/Document/Index/IndexerInterface.php b/Document/Index/IndexerInterface.php deleted file mode 100644 index 087e4eadb..000000000 --- a/Document/Index/IndexerInterface.php +++ /dev/null @@ -1,70 +0,0 @@ -nodeManager = $nodeManager; - $this->pathBuilder = $pathBuilder; - $this->sessionManager = $sessionManager; - } - - public function initialize(OutputInterface $output, $purge = false) - { - $nodeTypeManager = $this->sessionManager->getSession()->getWorkspace()->getNodeTypeManager(); - $nodeTypeManager->registerNodeType(new ArticleNodeType(), true); - $nodeTypeManager->registerNodeType(new ArticlePageNodeType(), true); - - $articlesPath = $this->pathBuilder->build(['%base%', '%articles%']); - if (true === $this->nodeManager->has($articlesPath)) { - $output->writeln(\sprintf(' [ ] Articles path:: %s ', $articlesPath)); - } else { - $output->writeln(\sprintf(' [+] Articles path:: %s ', $articlesPath)); - $this->nodeManager->createPath($articlesPath); - $this->nodeManager->save(); - } - } -} diff --git a/Document/Initializer/ArticleNodeType.php b/Document/Initializer/ArticleNodeType.php deleted file mode 100644 index c6361b556..000000000 --- a/Document/Initializer/ArticleNodeType.php +++ /dev/null @@ -1,67 +0,0 @@ -state = $state; - $this->locale = $locale; - } -} diff --git a/Document/LocalizedLastModifiedBehavior.php b/Document/LocalizedLastModifiedBehavior.php deleted file mode 100644 index fc55cfb7d..000000000 --- a/Document/LocalizedLastModifiedBehavior.php +++ /dev/null @@ -1,30 +0,0 @@ -id = $media->getId(); - $this->title = $media->getTitle(); - $this->setFormats($media->getFormats()); - $this->mimeType = $media->getMimeType(); - $this->url = $media->getUrl(); - $this->copyright = $media->getCopyright(); - - return $this; - } - - /** - * Get formats. - */ - public function getFormats(): string - { - return $this->formats; - } - - /** - * Set formats. - * - * @param string|string[] $formats - */ - public function setFormats($formats): self - { - if (\is_array($formats)) { - $formats = \json_encode($formats); - } - - $this->formats = $formats; - - return $this; - } - - /** - * Get thumbnails. - */ - public function getThumbnails(): array - { - return \json_decode($this->formats, true); - } -} diff --git a/Document/Repository/ArticleViewDocumentRepository.php b/Document/Repository/ArticleViewDocumentRepository.php deleted file mode 100644 index 1cb3926b8..000000000 --- a/Document/Repository/ArticleViewDocumentRepository.php +++ /dev/null @@ -1,168 +0,0 @@ -searchManager = $searchManager; - $this->articleDocumentClass = $articleDocumentClass; - $this->repository = $this->searchManager->getRepository($this->articleDocumentClass); - $this->searchFields = $searchFields; - } - - /** - * Finds recent articles for given parameters sorted by field `authored`. - */ - public function findRecent( - ?string $excludeUuid = null, - int $limit = self::DEFAULT_LIMIT, - ?array $types = null, - ?string $locale = null, - ?string $webspaceKey = null - ): DocumentIterator { - $search = $this->createSearch($limit, $types, $locale, $webspaceKey); - - if ($excludeUuid) { - $search->addQuery(new TermQuery('uuid', $excludeUuid), BoolQuery::MUST_NOT); - } - - $search->addSort(new FieldSort('authored', FieldSort::DESC)); - - return $this->repository->findDocuments($search); - } - - /** - * Finds similar articles for given `uuid` with given parameters. - */ - public function findSimilar( - string $uuid, - int $limit = self::DEFAULT_LIMIT, - ?array $types = null, - ?string $locale = null, - ?string $webspaceKey = null - ): DocumentIterator { - $search = $this->createSearch($limit, $types, $locale, $webspaceKey); - - $search->addQuery( - new MoreLikeThisQuery( - null, - [ - 'fields' => $this->searchFields, - 'min_term_freq' => 1, - 'min_doc_freq' => 2, - 'like' => [ - [ - '_id' => $this->getViewDocumentId($uuid, $locale), - ], - ], - ] - ) - ); - - return $this->repository->findDocuments($search); - } - - /** - * Creates search with default queries (size, locale, types, webspace). - */ - private function createSearch( - int $limit, - ?array $types = null, - ?string $locale = null, - ?string $webspaceKey = null - ): Search { - $search = $this->repository->createSearch(); - - // set size - $search->setSize($limit); - - // filter by locale if provided - if ($locale) { - $search->addQuery(new TermQuery('locale', $locale), BoolQuery::FILTER); - } - - // filter by types if provided - if ($types) { - $typesQuery = new BoolQuery(); - foreach ($types as $type) { - $typesQuery->add(new TermQuery('type', $type), BoolQuery::SHOULD); - } - $search->addQuery($typesQuery); - } - - // filter by webspace if provided - if ($webspaceKey) { - $webspaceQuery = new BoolQuery(); - - // check for mainWebspace - $webspaceQuery->add(new TermQuery('main_webspace', $webspaceKey), BoolQuery::SHOULD); - - // check for additionalWebspaces - $webspaceQuery->add(new TermQuery('additional_webspaces', $webspaceKey), BoolQuery::SHOULD); - - $search->addQuery($webspaceQuery); - } - - return $search; - } -} diff --git a/Document/Resolver/WebspaceResolver.php b/Document/Resolver/WebspaceResolver.php deleted file mode 100644 index f6e1aa248..000000000 --- a/Document/Resolver/WebspaceResolver.php +++ /dev/null @@ -1,85 +0,0 @@ -webspaceManager = $webspaceManager; - $this->webspaceSettingsConfigurationResolver = $webspaceSettingsConfigurationResolver; - } - - public function resolveMainWebspace(WebspaceBehavior $document): ?string - { - if (!$this->hasMoreThanOneWebspace()) { - $webspaces = $this->webspaceManager->getWebspaceCollection()->getWebspaces(); - - return \reset($webspaces)->getKey(); - } - - $hasCustomizedWebspaceSettings = $this->hasCustomizedWebspaceSettings($document); - - if ($hasCustomizedWebspaceSettings) { - return $document->getMainWebspace(); - } - - return $this->webspaceSettingsConfigurationResolver->getDefaultMainWebspaceForLocale($document->getOriginalLocale()); - } - - /** - * @return string[]|null - */ - public function resolveAdditionalWebspaces(WebspaceBehavior $document): ?array - { - if (!$this->hasMoreThanOneWebspace()) { - return []; - } - - $hasCustomizedWebspaceSettings = $this->hasCustomizedWebspaceSettings($document); - - if ($hasCustomizedWebspaceSettings) { - return $document->getAdditionalWebspaces() ?? []; - } - - return $this->webspaceSettingsConfigurationResolver->getDefaultAdditionalWebspacesForLocale($document->getOriginalLocale()); - } - - public function hasCustomizedWebspaceSettings(WebspaceBehavior $document): bool - { - return null !== $document->getMainWebspace(); - } - - /** - * Check if system has more than one webspace. - */ - private function hasMoreThanOneWebspace(): bool - { - return \count($this->webspaceManager->getWebspaceCollection()->getWebspaces()) > 1; - } -} diff --git a/Document/SegmentViewObject.php b/Document/SegmentViewObject.php deleted file mode 100644 index b85b22afe..000000000 --- a/Document/SegmentViewObject.php +++ /dev/null @@ -1,44 +0,0 @@ - Events::POST_SERIALIZE, - 'format' => 'json', - 'method' => 'addTitleOnPostSerialize', - ], - ]; - } - - /** - * Append title to result. - */ - public function addTitleOnPostSerialize(ObjectEvent $event): void - { - $articlePage = $event->getObject(); - /** @var SerializationVisitorInterface $visitor */ - $visitor = $event->getVisitor(); - - if (!$articlePage instanceof ArticlePageDocument) { - return; - } - - $title = $articlePage->getParent()->getTitle(); - $visitor->visitProperty(new StaticPropertyMetadata('', 'title', $title), $title); - } -} diff --git a/Document/Serializer/ArticleSubscriber.php b/Document/Serializer/ArticleSubscriber.php deleted file mode 100644 index d78f09e71..000000000 --- a/Document/Serializer/ArticleSubscriber.php +++ /dev/null @@ -1,219 +0,0 @@ -structureManager = $structureManager; - $this->structureMetadataFactory = $structureMetadataFactory; - $this->webspaceResolver = $webspaceResolver; - } - - public static function getSubscribedEvents() - { - return [ - [ - 'event' => Events::POST_SERIALIZE, - 'format' => 'json', - 'method' => 'addTypeOnPostSerialize', - ], - [ - 'event' => Events::POST_SERIALIZE, - 'format' => 'json', - 'method' => 'addWebspaceSettingsOnPostSerialize', - ], - [ - 'event' => Events::POST_SERIALIZE, - 'format' => 'json', - 'method' => 'addBrokenIndicatorOnPostSerialize', - ], - [ - 'event' => Events::POST_SERIALIZE, - 'format' => 'json', - 'method' => 'addPageTitlePropertyNameOnPostSerialize', - ], - ]; - } - - /** - * Append type to result. - */ - public function addTypeOnPostSerialize(ObjectEvent $event): void - { - $article = $event->getObject(); - /** @var SerializationVisitorInterface $visitor */ - $visitor = $event->getVisitor(); - - if (!($article instanceof ArticleDocument)) { - return; - } - - /** @var StructureBridge $structure */ - $structure = $this->structureManager->getStructure($article->getStructureType(), 'article'); - - $articleType = $this->getType($structure->getStructure()); - $visitor->visitProperty(new StaticPropertyMetadata('', 'articleType', $articleType), $articleType); - } - - /** - * Append webspace-settings to result. - */ - public function addWebspaceSettingsOnPostSerialize(ObjectEvent $event): void - { - $article = $event->getObject(); - /** @var SerializationVisitorInterface $visitor */ - $visitor = $event->getVisitor(); - - if (!($article instanceof ArticleDocument)) { - return; - } - - $hasCustomizedWebspaceSettings = $this->webspaceResolver->hasCustomizedWebspaceSettings($article); - $visitor->visitProperty( - new StaticPropertyMetadata('', 'customizeWebspaceSettings', $hasCustomizedWebspaceSettings), - $hasCustomizedWebspaceSettings - ); - if ($article->getMainWebspace()) { - return; - } - - $mainWebspace = $this->webspaceResolver->resolveMainWebspace($article); - $visitor->visitProperty(new StaticPropertyMetadata('', 'mainWebspace', $mainWebspace), $mainWebspace); - - $additionalWebspaces = $this->webspaceResolver->resolveAdditionalWebspaces($article); - $visitor->visitProperty( - new StaticPropertyMetadata('', 'additionalWebspaces', $additionalWebspaces), - $additionalWebspaces - ); - } - - /** - * Append broken-indicator to result. - */ - public function addBrokenIndicatorOnPostSerialize(ObjectEvent $event): void - { - $article = $event->getObject(); - /** @var SerializationVisitorInterface $visitor */ - $visitor = $event->getVisitor(); - - if (!($article instanceof ArticleViewDocumentInterface)) { - return; - } - - $structure = $this->structureManager->getStructure($article->getStructureType(), 'article'); - - $broken = (!$structure || $structure->getKey() !== $article->getStructureType()); - $visitor->visitProperty( - new StaticPropertyMetadata('', 'broken', $broken), - $broken - ); - - $originalStructureType = $article->getStructureType(); - $visitor->visitProperty( - new StaticPropertyMetadata('', 'originalStructureType', $originalStructureType), - $originalStructureType - ); - } - - /** - * Append page-title-property to result. - */ - public function addPageTitlePropertyNameOnPostSerialize(ObjectEvent $event): void - { - $article = $event->getObject(); - /** @var SerializationVisitorInterface $visitor */ - $visitor = $event->getVisitor(); - - if (!$article instanceof ArticleInterface) { - return; - } - - $property = $this->getPageTitleProperty($article); - if ($property) { - $propertyName = $property->getName(); - $visitor->visitProperty( - new StaticPropertyMetadata('', '_pageTitlePropertyName', $propertyName), - $propertyName - ); - } - } - - /** - * Find page-title property. - */ - private function getPageTitleProperty(ArticleInterface $document): ?PropertyMetadata - { - $metadata = $this->structureMetadataFactory->getStructureMetadata( - 'article', - $document->getStructureType() - ); - - if ($metadata->hasPropertyWithTagName(self::PAGE_TITLE_TAG_NAME)) { - return $metadata->getPropertyByTagName(self::PAGE_TITLE_TAG_NAME); - } - - if ($metadata->hasProperty(self::PAGE_TITLE_PROPERTY_NAME)) { - return $metadata->getProperty(self::PAGE_TITLE_PROPERTY_NAME); - } - - return null; - } -} diff --git a/Document/Serializer/WebsiteArticleUrlsSubscriber.php b/Document/Serializer/WebsiteArticleUrlsSubscriber.php deleted file mode 100644 index 2bd0d3a80..000000000 --- a/Document/Serializer/WebsiteArticleUrlsSubscriber.php +++ /dev/null @@ -1,218 +0,0 @@ -requestStack = $requestStack; - $this->routeRepository = $routeRepository; - $this->webspaceManager = $webspaceManager; - $this->documentInspector = $documentInspector; - $this->documentRegistry = $documentRegistry; - $this->nodeManager = $nodeManager; - - if (null === $this->documentInspector) { - @\trigger_error( - 'Instantiating the WebsiteArticleUrlsSubscriber without the $documentInspector argument is deprecated!', - \E_USER_DEPRECATED - ); - } - - if (null === $this->documentRegistry) { - @\trigger_error( - 'Instantiating the WebsiteArticleUrlsSubscriber without the $documentRegistry argument is deprecated!', - \E_USER_DEPRECATED - ); - } - - if (null === $this->nodeManager) { - @\trigger_error( - 'Instantiating the WebsiteArticleUrlsSubscriber without the $nodeManager argument is deprecated!', - \E_USER_DEPRECATED - ); - } - } - - public static function getSubscribedEvents() - { - return [ - [ - 'event' => Events::POST_SERIALIZE, - 'format' => 'json', - 'method' => 'addUrlsOnPostSerialize', - ], - ]; - } - - /** - * Loops thru current webspace locales and generates routes for them. - */ - public function addUrlsOnPostSerialize(ObjectEvent $event): void - { - $article = $event->getObject(); - /** @var SerializationVisitorInterface $visitor */ - $visitor = $event->getVisitor(); - $context = $event->getContext(); - $request = $this->requestStack->getCurrentRequest(); - - if (!$article instanceof ArticleDocument || !$context->hasAttribute('urls') || !$request) { - return; - } - - /** @var RequestAttributes $attributes */ - $attributes = $request->get('_sulu'); - if (!$attributes) { - return; - } - - /** @var Webspace $webspace */ - $webspace = $attributes->getAttribute('webspace'); - if (!$webspace) { - return; - } - - if (null !== ($portal = $attributes->getAttribute('portal'))) { - $allLocalizations = $portal->getLocalizations(); - } else { - $allLocalizations = $webspace->getAllLocalizations(); - } - - $urls = []; - $localizations = []; - $publishedLocales = $this->getPublishedLocales($article, $webspace); - - foreach ($allLocalizations as $localization) { - $locale = $localization->getLocale(); - $published = \in_array($locale, $publishedLocales, true); - $path = '/'; - $alternate = false; - - if ($published) { - $route = $this->routeRepository->findByEntity(\get_class($article), $article->getUuid(), $locale); - - if ($route) { - $path = $route->getPath(); - $alternate = true; - } - } - - $urls[$locale] = $path; - $localizations[$locale] = [ - 'locale' => $locale, - 'url' => $this->webspaceManager->findUrlByResourceLocator($path, null, $locale), - 'country' => $localization->getCountry(), - 'alternate' => $alternate, - ]; - } - - $visitor->visitProperty(new StaticPropertyMetadata('', 'urls', $urls), $urls); - $visitor->visitProperty(new StaticPropertyMetadata('', 'localizations', $localizations), $localizations); - } - - /** - * @return string[] - */ - private function getWebspaceLocales(Webspace $webspace): array - { - return \array_map( - function(Localization $localization) { - return $localization->getLocale(); - }, - $webspace->getAllLocalizations() - ); - } - - /** - * @return string[] - */ - private function getPublishedLocales(ArticleDocument $document, Webspace $webspace): array - { - if (null === $this->documentInspector || null === $this->documentRegistry || null === $this->nodeManager) { - // BC layer - return $this->getWebspaceLocales($webspace); - } - - // In the preview, the ArticleDocument is not registered in the DocumentRegistry, because this usually - // happens automatically when calling DocumentManager::find(), which is not done for the preview, but the - // DocumentInspector::getPublishedLocales() requires it to be registered. - // Therefore we need to register it manually in that case. - if (!$this->documentRegistry->hasDocument($document)) { - try { - $node = $this->nodeManager->find($document->getUuid()); - } catch (DocumentNotFoundException $e) { - return []; - } - - $this->documentRegistry->registerDocument($document, $node, $document->getLocale()); - } - - return $this->documentInspector->getPublishedLocales($document); - } -} diff --git a/Document/Structure/ArticleBridge.php b/Document/Structure/ArticleBridge.php deleted file mode 100644 index 4819afc26..000000000 --- a/Document/Structure/ArticleBridge.php +++ /dev/null @@ -1,124 +0,0 @@ -structure->getView(); - } - - public function getController(): string - { - /** @var string */ - return $this->structure->getController(); - } - - /** - * @return array{type: string, value: string} - */ - public function getCacheLifeTime(): array - { - /** @var array{type: string, value: string} */ - return $this->structure->getCacheLifetime(); - } - - public function getUuid() - { - // is set for structure loaded with document from document-manager - // is not set when using structure with view-document - if ($this->document) { - return parent::getUuid(); - } - - return $this->uuid; - } - - public function setUuid($uuid) - { - $this->uuid = $uuid; - } - - /** - * Will be called by SuluCollector to collect profiler data. - */ - public function getNavContexts() - { - return null; - } - - public function getEnabledShadowLanguages(): array - { - return $this->inspector->getShadowLocales($this->getDocument()); - } - - public function getConcreteLanguages(): array - { - return $this->inspector->getConcreteLocales($this->getDocument()); - } - - /** - * @return mixed - * - * Will be called by SuluCollector to collect profiler data - */ - public function getOriginTemplate() - { - return null; - } - - public function getExt() - { - return $this->document->getExtensionsData(); - } - - public function getWebspaceKey() - { - return $this->webspaceKey; - } - - public function setWebspaceKey($webspace) - { - $this->webspaceKey = $webspace; - } - - public function getLanguageCode() - { - if (!$this->document) { - return $this->locale; - } - - // return original locale for shadow or ghost pages - if ($this->getIsShadow() || ($this->getType() && 'ghost' === $this->getType()->getName())) { - return $this->inspector->getOriginalLocale($this->getDocument()); - } - - return parent::getLanguageCode(); - } -} diff --git a/Document/Structure/ArticlePageBridge.php b/Document/Structure/ArticlePageBridge.php deleted file mode 100644 index 6fee73d77..000000000 --- a/Document/Structure/ArticlePageBridge.php +++ /dev/null @@ -1,19 +0,0 @@ -contentTypeManager = $contentTypeManager; - $this->proxyFactory = $proxyFactory; - $this->requestStack = $requestStack; - } - - /** - * Create content-proxy for given structure. - * - * @return VirtualProxyInterface - */ - public function createContentProxy(StructureInterface $structure, array $data) - { - return $this->proxyFactory->createProxy( - \ArrayObject::class, - function( - &$wrappedObject, - LazyLoadingInterface $proxy, - $method, - array $parameters, - &$initializer - ) use ($structure, $data) { - $initializer = null; - $wrappedObject = new \ArrayObject($this->resolveContent($structure, $data)); - - return true; - } - ); - } - - /** - * Resolve content from given data with the structure. - */ - private function resolveContent(StructureInterface $structure, array $data): array - { - $structure->setWebspaceKey($this->getWebspaceKey()); - - $content = []; - foreach ($structure->getProperties(true) as $child) { - if (\array_key_exists($child->getName(), $data)) { - $child->setValue($data[$child->getName()]); - } - - $contentType = $this->contentTypeManager->get($child->getContentTypeName()); - $content[$child->getName()] = $contentType->getContentData($child); - } - - return $content; - } - - /** - * Create view-proxy for given structure. - * - * @return VirtualProxyInterface - */ - public function createViewProxy(StructureInterface $structure, array $data) - { - return $this->proxyFactory->createProxy( - \ArrayObject::class, - function( - &$wrappedObject, - LazyLoadingInterface $proxy, - $method, - array $parameters, - &$initializer - ) use ($structure, $data) { - $initializer = null; - $wrappedObject = new \ArrayObject($this->resolveView($structure, $data)); - - return true; - } - ); - } - - /** - * Resolve view from given data with the structure. - */ - private function resolveView(StructureInterface $structure, array $data): array - { - $structure->setWebspaceKey($this->getWebspaceKey()); - - $view = []; - foreach ($structure->getProperties(true) as $child) { - if (\array_key_exists($child->getName(), $data)) { - $child->setValue($data[$child->getName()]); - } - - $contentType = $this->contentTypeManager->get($child->getContentTypeName()); - $view[$child->getName()] = $contentType->getViewData($child); - } - - return $view; - } - - private function getWebspaceKey(): ?string - { - $request = $this->requestStack->getCurrentRequest(); - if (!$request) { - return null; - } - - /** @var RequestAttributes $attributes */ - $attributes = $request->attributes->get('_sulu'); - if (!$attributes) { - return null; - } - - return $attributes->getAttribute('webspaceKey') ?? $attributes->getAttribute('webspace')->getKey(); - } -} diff --git a/Document/Structure/RoutableStructureInterface.php b/Document/Structure/RoutableStructureInterface.php deleted file mode 100644 index bb9c95bae..000000000 --- a/Document/Structure/RoutableStructureInterface.php +++ /dev/null @@ -1,61 +0,0 @@ -structureMetadataFactory = $structureMetadataFactory; - $this->documentManager = $documentManager; - $this->documentInspector = $documentInspector; - $this->slugifier = $slugifier; - $this->resolver = $resolver; - } - - public static function getSubscribedEvents() - { - return [ - Events::HYDRATE => [ - ['setParentOnHydrate', 1], - ], - Events::PERSIST => [ - ['checkOptions', 10000], - ['setTitleOnPersist', 2000], - ['setNodeOnPersist', 480], - ['setPageTitleOnPersist'], - ['setStructureTypeToParent', -2000], - ['setWorkflowStageOnArticle', -2000], - ], - Events::REMOVE => ['setWorkflowStageOnArticle'], - Events::METADATA_LOAD => ['handleMetadataLoad'], - ]; - } - - /** - * Hydrate parent to avoid proxiing it. - */ - public function setParentOnHydrate(HydrateEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument || $document->getParent()) { - return; - } - - $parent = $this->documentManager->find( - $event->getNode()->getParent()->getIdentifier(), - $document->getOriginalLocale(), - $event->getOptions() - ); - $document->setParent($parent); - } - - /** - * Check for missing persist options. - */ - public function checkOptions(PersistEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument) { - return; - } - - $autoRename = $event->getOption('auto_rename'); - - if (false !== $autoRename) { - throw new \InvalidArgumentException('Persist "ArticlePageDocument" only with option "auto_rename" set to "false" allowed'); - } - } - - /** - * Set page-title from structure to document. - */ - public function setTitleOnPersist(PersistEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument) { - return; - } - - $document->setTitle($document->getParent()->getTitle()); - } - - /** - * Set workflow-stage to test for article. - * - * @param PersistEvent|RemoveEvent $event - */ - public function setWorkflowStageOnArticle($event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument - || LocalizationState::GHOST === $this->documentInspector->getLocalizationState($document->getParent()) - ) { - return; - } - - $document->getParent()->setWorkflowStage(WorkflowStage::TEST); - /** @var array $options */ - $options = $event instanceof PersistEvent ? $event->getOptions() : []; - $this->documentManager->persist( - $document->getParent(), - $this->documentInspector->getLocale($document), - $options - ); - } - - /** - * Set node to event on persist. - */ - public function setNodeOnPersist(PersistEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument || $event->hasNode()) { - return; - } - - $pageTitle = $this->getPageTitle($document); - - // if no page-title exists use a unique-id - $nodeName = $this->slugifier->slugify($pageTitle ?: \uniqid('page-', true)); - $nodeName = $this->resolver->resolveName($event->getParentNode(), $nodeName); - $node = $event->getParentNode()->addNode($nodeName); - - $event->setNode($node); - } - - /** - * Set page-title on persist event. - */ - public function setPageTitleOnPersist(PersistEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleInterface || !\method_exists($document, 'setPageTitle')) { - return; - } - - $document->setPageTitle($this->getPageTitle($document)); - } - - /** - * Returns page-title for node. - */ - private function getPageTitle(ArticleInterface $document): ?string - { - $pageTitleProperty = $this->getPageTitleProperty($document); - if (!$pageTitleProperty) { - return null; - } - - $stagedData = $document->getStructure()->getStagedData(); - if (\array_key_exists($pageTitleProperty->getName(), $stagedData)) { - return $stagedData[$pageTitleProperty->getName()]; - } - - if (!$document->getStructure()->hasProperty($pageTitleProperty->getName())) { - return null; - } - - return $document->getStructure()->getProperty($pageTitleProperty->getName())->getValue(); - } - - /** - * Find page-title property. - */ - private function getPageTitleProperty(ArticleInterface $document): ?PropertyMetadata - { - $metadata = $this->structureMetadataFactory->getStructureMetadata( - 'article_page', - $document->getStructureType() - ); - - if ($metadata->hasPropertyWithTagName(self::PAGE_TITLE_TAG_NAME)) { - return $metadata->getPropertyByTagName(self::PAGE_TITLE_TAG_NAME); - } - - if ($metadata->hasProperty(self::PAGE_TITLE_PROPERTY_NAME)) { - return $metadata->getProperty(self::PAGE_TITLE_PROPERTY_NAME); - } - - return null; - } - - /** - * Set structure-type to parent document. - */ - public function setStructureTypeToParent(PersistEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument - || LocalizationState::GHOST === $this->documentInspector->getLocalizationState($document->getParent()) - || $document->getStructureType() === $document->getParent()->getStructureType() - ) { - return; - } - - $document->getParent()->setStructureType($document->getStructureType()); - $this->documentManager->persist($document->getParent(), $event->getLocale()); - } - - /** - * Extend metadata for article-page. - */ - public function handleMetadataLoad(MetadataLoadEvent $event): void - { - if (ArticlePageDocument::class !== $event->getMetadata()->getClass() - && !\is_subclass_of($event->getMetadata()->getClass(), ArticlePageDocument::class) - ) { - return; - } - - $metadata = $event->getMetadata(); - $metadata->setSyncRemoveLive(false); - $metadata->addFieldMapping( - 'pageTitle', - [ - 'encoding' => 'system_localized', - 'property' => 'suluPageTitle', - ] - ); - } -} diff --git a/Document/Subscriber/ArticleSubscriber.php b/Document/Subscriber/ArticleSubscriber.php deleted file mode 100644 index 1d0f114a6..000000000 --- a/Document/Subscriber/ArticleSubscriber.php +++ /dev/null @@ -1,599 +0,0 @@ -indexer = $indexer; - $this->liveIndexer = $liveIndexer; - $this->documentManager = $documentManager; - $this->documentInspector = $documentInspector; - $this->propertyEncoder = $propertyEncoder; - } - - public static function getSubscribedEvents() - { - return [ - Events::HYDRATE => [ - ['hydratePageData', -2000], - ], - Events::PERSIST => [ - ['handleScheduleIndex', -500], - ['handleChildrenPersist', 0], - ['persistPageData', -2000], - ], - Events::REMOVE => [ - ['handleRemove', -500], - ['handleRemoveLive', -500], - ['handleRemovePage', -500], - ], - Events::PUBLISH => [ - ['handleScheduleIndexLive', 0], - ['handleScheduleIndex', 0], - ['synchronizeChildren', 0], - ['publishChildren', 0], - ['persistPageData', -2000], - ], - Events::REORDER => [['persistPageDataOnReorder', -2000]], - Events::UNPUBLISH => 'handleUnpublish', - Events::REMOVE_DRAFT => [['handleScheduleIndex', -1024], ['removeDraftChildren', 0]], - Events::FLUSH => [['handleFlush', -2048], ['handleFlushLive', -2048]], - Events::COPY => ['handleCopy'], - Events::METADATA_LOAD => ['handleMetadataLoad'], - Events::REMOVE_LOCALE => [['handleRemoveLocale', -500], ['handleRemoveLocaleLive', -500]], - ]; - } - - /** - * Schedule article document for index. - */ - public function handleScheduleIndex(AbstractMappingEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - if (!$document instanceof ArticlePageDocument) { - return; - } - - $document = $document->getParent(); - } - - $this->documents[$document->getUuid() . '_' . $document->getLocale()] = [ - 'uuid' => $document->getUuid(), - 'locale' => $document->getLocale(), - ]; - } - - /** - * Schedule article document for live index. - */ - public function handleScheduleIndexLive(AbstractMappingEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - if (!$document instanceof ArticlePageDocument) { - return; - } - - $document = $document->getParent(); - } - - $this->liveDocuments[$document->getUuid() . '_' . $document->getLocale()] = [ - 'uuid' => $document->getUuid(), - 'locale' => $document->getLocale(), - ]; - } - - /** - * Syncs children between live and draft. - */ - public function synchronizeChildren(PublishEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $liveNode = $event->getNode(); - $draftNode = $this->documentInspector->getNode($document); - - $liveChildren = $this->getChildren($liveNode); - $draftChildren = $this->getChildren($draftNode); - $removedChildrenIds = \array_diff(\array_keys($liveChildren), \array_keys($draftChildren)); - - foreach ($removedChildrenIds as $removedChildrenId) { - $liveChildren[$removedChildrenId]->remove(); - } - } - - /** - * Returns children of given node. - * - * @return NodeInterface[] - */ - private function getChildren(NodeInterface $node): array - { - $result = []; - foreach ($node->getNodes() as $child) { - $result[$child->getIdentifier()] = $child; - } - - return $result; - } - - /** - * Publish pages when article will be published. - */ - public function publishChildren(PublishEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $children = \iterator_to_array($document->getChildren()); - foreach ($children as $child) { - if (LocalizationState::GHOST !== $this->documentInspector->getLocalizationState($child)) { - $this->documentManager->publish($child, $event->getLocale()); - } - } - } - - /** - * Persist page-data for reordering children. - */ - public function persistPageDataOnReorder(ReorderEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument) { - return; - } - - $document = $document->getParent(); - $node = $this->documentInspector->getNode($document); - - $this->setPageData($document, $node, $document->getLocale()); - - $document->setWorkflowStage(WorkflowStage::TEST); - $this->documentManager->persist($document, $this->documentInspector->getLocale($document)); - - $this->documents[$document->getUuid() . '_' . $document->getLocale()] = [ - 'uuid' => $document->getUuid(), - 'locale' => $document->getLocale(), - ]; - } - - /** - * Persist page-data. - * - * @param PersistEvent|PublishEvent $event - */ - public function persistPageData($event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $this->setPageData($document, $event->getNode(), $event->getLocale()); - } - - /** - * Set page-data for given document on given node. - */ - private function setPageData(ArticleDocument $document, NodeInterface $node, string $locale): void - { - $pages = [ - [ - 'uuid' => $document->getUuid(), - 'title' => $document->getPageTitle() ?: $document->getTitle(), - 'routePath' => $document->getRoutePath(), - 'pageNumber' => $document->getPageNumber(), - ], - ]; - - foreach ($document->getChildren() as $child) { - if ($child instanceof ArticlePageDocument - && LocalizationState::GHOST !== $this->documentInspector->getLocalizationState($child) - ) { - $pages[] = [ - 'uuid' => $child->getUuid(), - 'title' => $child->getPageTitle(), - 'routePath' => $child->getRoutePath(), - 'pageNumber' => $child->getPageNumber(), - ]; - } - } - - $pages = SortUtils::multisort($pages, '[pageNumber]'); - - $document->setPages($pages); - $node->setProperty( - $this->propertyEncoder->localizedSystemName(self::PAGES_PROPERTY, $locale), - \json_encode($pages) - ); - } - - /** - * Hydrate page-data. - */ - public function hydratePageData(HydrateEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $pages = $event->getNode()->getPropertyValueWithDefault( - $this->propertyEncoder->localizedSystemName(self::PAGES_PROPERTY, $document->getOriginalLocale()), - \json_encode([]) - ); - $pages = \json_decode($pages, true); - - if (LocalizationState::SHADOW === $this->documentInspector->getLocalizationState($document)) { - $pages = $this->loadPageDataForShadow($event->getNode(), $document, $pages); - } - - $document->setPages($pages); - } - - /** - * Load `routePath` from current locale into `pageData`. - */ - private function loadPageDataForShadow(NodeInterface $node, ArticleDocument $document, array $originalPages): array - { - $pages = $node->getPropertyValueWithDefault( - $this->propertyEncoder->localizedSystemName(self::PAGES_PROPERTY, $document->getLocale()), - \json_encode([]) - ); - $pages = \json_decode($pages, true); - - for ($i = 0; $i < \count($originalPages); ++$i) { - $pages[$i]['routePath'] = $originalPages[$i]['routePath']; - } - - return $pages; - } - - /** - * Remove draft from children. - */ - public function removeDraftChildren(RemoveDraftEvent $event) - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - foreach ($document->getChildren() as $child) { - if (LocalizationState::GHOST === $this->documentInspector->getLocalizationState($child)) { - continue; - } - - try { - $this->documentManager->removeDraft($child, $event->getLocale()); - } catch (PathNotFoundException $exception) { - // child is not available in live workspace - $node = $this->documentInspector->getNode($child); - $node->remove(); - } - } - } - - /** - * Index all scheduled article documents with default indexer. - */ - public function handleFlush(FlushEvent $event): void - { - if (\count($this->documents) < 1) { - return; - } - - foreach ($this->documents as $documentData) { - /** @var ArticleDocument|null $document */ - $document = $this->documentManager->find($documentData['uuid'], $documentData['locale']); - $this->documentManager->refresh($document); - - $this->indexer->index($document); - } - $this->indexer->flush(); - $this->documents = []; - } - - /** - * Index all scheduled article documents with live indexer. - */ - public function handleFlushLive(FlushEvent $event): void - { - if (\count($this->liveDocuments) < 1) { - return; - } - - foreach ($this->liveDocuments as $documentData) { - /** @var ArticleDocument|null $document */ - $document = $this->documentManager->find($documentData['uuid'], $documentData['locale']); - $this->documentManager->refresh($document); - - $this->liveIndexer->index($document); - } - $this->liveIndexer->flush(); - $this->liveDocuments = []; - } - - /** - * Removes document from live index and unpublish document in default index. - */ - public function handleUnpublish(UnpublishEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $this->liveIndexer->remove($document, $event->getLocale()); - $this->liveIndexer->flush(); - - $this->indexer->setUnpublished($document->getUuid(), $event->getLocale()); - $this->indexer->flush(); - } - - /** - * Reindex article if a page was removed. - */ - public function handleRemovePage(RemoveEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticlePageDocument) { - return; - } - - $document = $document->getParent(); - $this->documents[$document->getUuid() . '_' . $document->getLocale()] = [ - 'uuid' => $document->getUuid(), - 'locale' => $document->getLocale(), - ]; - } - - /** - * Removes article-document. - */ - public function handleRemove(RemoveEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $this->indexer->remove($document); - $this->indexer->flush(); - } - - /** - * Removes localized article-document. - */ - public function handleRemoveLocale(RemoveLocaleEvent $event) - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $concreteLocales = $this->documentInspector->getConcreteLocales($document); - $ghostLocale = $document->getOriginalLocale(); - if (!\in_array($ghostLocale, $concreteLocales, true)) { - $ghostLocale = $concreteLocales[0] ?? null; - } - - if (null !== $ghostLocale) { - /** @var ArticleDocument $document */ - $document = $this->documentManager->find($document->getUuid(), $ghostLocale); - } - - $this->indexer->replaceWithGhostData($document, $event->getLocale()); - $this->indexer->flush(); - } - - /** - * Removes article-document. - * - * @param RemoveEvent|UnpublishEvent $event - */ - public function handleRemoveLive($event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $this->liveIndexer->remove($document); - $this->liveIndexer->flush(); - } - - /** - * Removes localized article-document from live index. - */ - public function handleRemoveLocaleLive(RemoveLocaleEvent $event) - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $this->liveIndexer->remove($document, $event->getLocale()); - $this->liveIndexer->flush(); - } - - /** - * Schedule document to index. - */ - public function handleCopy(CopyEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - $uuid = $event->getCopiedNode()->getIdentifier(); - $this->documents[$uuid . '_' . $document->getLocale()] = [ - 'uuid' => $uuid, - 'locale' => $document->getLocale(), - ]; - } - - /** - * Schedule all children. - */ - public function handleChildrenPersist(PersistEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleDocument) { - return; - } - - foreach ($document->getChildren() as $childDocument) { - if (!$childDocument instanceof ArticlePageDocument) { - continue; - } - - $localizationState = $this->documentInspector->getLocalizationState($childDocument); - - if (LocalizationState::GHOST === $localizationState) { - continue; - } - - $changed = false; - - if ($document->getStructureType() !== $childDocument->getStructureType()) { - $childDocument->setStructureType($document->getStructureType()); - $changed = true; - } - - if ($document->getShadowLocale() !== $childDocument->getShadowLocale()) { - $childDocument->setShadowLocale($document->getShadowLocale()); - $changed = true; - } - - if ($document->isShadowLocaleEnabled() !== $childDocument->isShadowLocaleEnabled()) { - $childDocument->setShadowLocaleEnabled($document->isShadowLocaleEnabled()); - $changed = true; - } - - if ($changed) { - $this->documentManager->persist( - $childDocument, - $childDocument->getLocale(), - [ - 'clear_missing_content' => false, - 'auto_name' => false, - 'auto_rename' => false, - ] - ); - } - } - } - - /** - * Extend metadata for article-page. - */ - public function handleMetadataLoad(MetadataLoadEvent $event): void - { - if (ArticleDocument::class !== $event->getMetadata()->getClass()) { - return; - } - - $event->getMetadata()->addFieldMapping( - 'pageTitle', - [ - 'encoding' => 'system_localized', - 'property' => 'suluPageTitle', - ] - ); - } -} diff --git a/Document/Subscriber/DateShardingSubscriber.php b/Document/Subscriber/DateShardingSubscriber.php deleted file mode 100644 index 738d9fe2b..000000000 --- a/Document/Subscriber/DateShardingSubscriber.php +++ /dev/null @@ -1,71 +0,0 @@ -pathBuilder = $pathBuilder; - $this->nodeManager = $nodeManager; - } - - public static function getSubscribedEvents() - { - return [ - Events::PERSIST => [ - ['handleSetParentNode', 481], - ], - ]; - } - - /** - * Set parent-node if no parent exists. - * - * The format of parent node is: /%base%/%articles%/ - */ - public function handleSetParentNode(PersistEvent $event): void - { - if (!$event->getDocument() instanceof DateShardingBehavior || $event->hasParentNode()) { - return; - } - - $date = $event->getDocument()->getCreated(); - if (null === $date) { - $date = new \DateTime(); - } - - $path = $this->pathBuilder->build(['%base%', '%articles%', $date->format('Y'), $date->format('m')]); - - $event->setParentNode($this->nodeManager->createPath($path)); - } -} diff --git a/Document/Subscriber/PageSubscriber.php b/Document/Subscriber/PageSubscriber.php deleted file mode 100644 index 9dbc1ac0e..000000000 --- a/Document/Subscriber/PageSubscriber.php +++ /dev/null @@ -1,200 +0,0 @@ -documentInspector = $documentInspector; - $this->propertyEncoder = $propertyEncoder; - $this->documentManager = $documentManager; - } - - public static function getSubscribedEvents() - { - return [ - Events::HYDRATE => ['handleHydrate'], - Events::PERSIST => [['handlePersist', -1024]], - Events::REMOVE => [['handleRemove', 5]], - Events::PUBLISH => [['handlePublishPageNumber', -1024]], - Events::REORDER => [['handleReorder', 0]], - Events::RESTORE => [['handleRestore', -1024]], - ]; - } - - /** - * Set the page-number to existing pages. - */ - public function handleHydrate(HydrateEvent $event): void - { - $document = $event->getDocument(); - $node = $event->getNode(); - $propertyName = $this->propertyEncoder->systemName(static::FIELD); - if (!$document instanceof PageBehavior || !$node->hasProperty($propertyName)) { - return; - } - - $node = $event->getNode(); - $document->setPageNumber($node->getPropertyValue($this->propertyEncoder->systemName(static::FIELD))); - } - - /** - * Set the page-number to new pages. - */ - public function handlePersist(PersistEvent $event): void - { - $document = $event->getDocument(); - $node = $event->getNode(); - $propertyName = $this->propertyEncoder->systemName(static::FIELD); - if (!$document instanceof PageBehavior) { - return; - } - - $parentDocument = $document->getParent(); - - $page = 1; - foreach ($parentDocument->getChildren() as $child) { - if (!$child instanceof PageBehavior) { - continue; - } - - ++$page; - - if ($child === $document) { - break; - } - } - - $node->setProperty($propertyName, $page); - $document->setPageNumber($page); - } - - /** - * Adjust the page-numbers of siblings when reordering a page. - */ - public function handleReorder(ReorderEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof PageBehavior) { - return; - } - - $propertyName = $this->propertyEncoder->systemName(static::FIELD); - $parentNode = $this->documentInspector->getNode($document->getParent()); - - $page = 1; - foreach ($parentNode->getNodes() as $childNode) { - $child = $this->documentManager->find($childNode->getIdentifier(), $event->getLocale()); - if (!$child instanceof PageBehavior) { - continue; - } - - $childNode->setProperty($propertyName, ++$page); - $child->setPageNumber($page); - } - } - - /** - * Copy page-number to live workspace. - */ - public function handlePublishPageNumber(PublishEvent $event): void - { - $document = $event->getDocument(); - $node = $event->getNode(); - $propertyName = $this->propertyEncoder->systemName(static::FIELD); - if (!$document instanceof PageBehavior) { - return; - } - - $node->setProperty($propertyName, $document->getPageNumber()); - } - - /** - * Adjust the page-numbers of siblings when removing a page. - */ - public function handleRemove(RemoveEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof PageBehavior) { - return; - } - - $page = 1; - foreach ($document->getParent()->getChildren() as $child) { - if (!$child instanceof PageBehavior || $child->getUuid() === $document->getUuid()) { - continue; - } - - $childNode = $this->documentInspector->getNode($child); - $childNode->setProperty($this->propertyEncoder->systemName(static::FIELD), ++$page); - } - } - - /** - * Adjust the page-numbers of siblings when restoring a page. - */ - public function handleRestore(RestoreEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ChildrenBehavior) { - return; - } - - $page = 1; - foreach ($document->getChildren() as $child) { - if (!$child instanceof PageBehavior) { - continue; - } - - $childNode = $this->documentInspector->getNode($child); - $childNode->setProperty($this->propertyEncoder->systemName(static::FIELD), ++$page); - } - } -} diff --git a/Document/Subscriber/RoutableSubscriber.php b/Document/Subscriber/RoutableSubscriber.php deleted file mode 100644 index 2ac291072..000000000 --- a/Document/Subscriber/RoutableSubscriber.php +++ /dev/null @@ -1,432 +0,0 @@ -chainRouteGenerator = $chainRouteGenerator; - $this->routeManager = $routeManager; - $this->routeRepository = $routeRepository; - $this->entityManager = $entityManager; - $this->documentManager = $documentManager; - $this->documentInspector = $documentInspector; - $this->propertyEncoder = $propertyEncoder; - $this->metadataFactory = $metadataFactory; - $this->conflictResolver = $conflictResolver; - } - - public static function getSubscribedEvents(): array - { - return [ - Events::PERSIST => [ - // low priority because all other subscriber should be finished - ['handlePersist', -2048], - ], - Events::REMOVE => [ - // high priority to ensure nodes are not deleted until we iterate over children - ['handleRemove', 2048], - ], - Events::PUBLISH => ['handlePublish', -2048], - Events::REORDER => ['handleReorder', -1024], - Events::COPY => ['handleCopy', -2048], - ]; - } - - /** - * Generate route and save route-path. - */ - public function handlePersist(AbstractMappingEvent $event): void - { - $document = $event->getDocument(); - - if (!$document instanceof RoutablePageBehavior || !$document instanceof ChildrenBehavior) { - return; - } - - $this->updateChildRoutes($document); - } - - /** - * Regenerate routes for siblings on reorder. - */ - public function handleReorder(ReorderEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof RoutablePageBehavior || !$document instanceof ParentBehavior) { - return; - } - - $parentDocument = $document->getParent(); - if (!$parentDocument instanceof ChildrenBehavior) { - return; - } - - $this->updateChildRoutes($parentDocument); - } - - /** - * Handle publish event and generate route and the child-routes. - * - * @throws ResourceLocatorAlreadyExistsException - */ - public function handlePublish(PublishEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof RoutableBehavior) { - return; - } - - $propertyName = $this->getPropertyName($event->getLocale(), self::ROUTES_PROPERTY); - - // check if nodes previous generated routes exists and remove them if not - $oldRoutes = $event->getNode()->getPropertyValueWithDefault($propertyName, []); - $this->removeOldChildRoutes($event->getNode()->getSession(), $oldRoutes, $event->getLocale()); - - $routes = []; - if ($document instanceof ChildrenBehavior) { - // generate new routes of children - $routes = $this->generateChildRoutes($document, $event->getLocale()); - } - - // save the newly generated routes of children - $event->getNode()->setProperty($propertyName, $routes); - $this->entityManager->flush(); - } - - /** - * Removes route. - */ - public function handleRemove(RemoveEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof RoutableBehavior || !$document instanceof ChildrenBehavior) { - return; - } - - $locales = $this->documentInspector->getLocales($document); - foreach ($locales as $locale) { - $this->removeChildRoutes($document, $locale); - } - - $this->entityManager->flush(); - } - - /** - * Update routes for copied article. - */ - public function handleCopy(CopyEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof RoutableBehavior) { - return; - } - - $locales = $this->documentInspector->getLocales($document); - foreach ($locales as $locale) { - $localizedDocument = $this->documentManager->find($event->getCopiedPath(), $locale); - - if ($localizedDocument instanceof ChildrenBehavior) { - $this->generateChildRoutes($localizedDocument, $locale); - } - } - } - - /** - * Create or update for given document. - */ - private function createOrUpdatePageRoute(RoutablePageBehavior $document, string $locale): RouteInterface - { - $route = $this->reallocateExistingRoute($document, $locale); - if ($route) { - return $route; - } - - $route = $document->getRoute(); - if (!$route) { - $route = $this->routeRepository->findByEntity($document->getClass(), $document->getUuid(), $locale); - } - - if ($route && $route->getEntityId() !== $document->getId()) { - // Mismatch of entity-id's happens because doctrine don't check entities which has been changed in the - // current session. - - $document->removeRoute(); - $route = null; - } - - if ($route) { - $document->setRoute($route); - - return $this->routeManager->update($document, null, false); - } - - return $this->routeManager->create($document); - } - - /** - * Reallocates existing route to given document. - */ - private function reallocateExistingRoute(RoutablePageBehavior $document, string $locale): ?RouteInterface - { - $newRoute = $this->routeRepository->findByPath($document->getRoutePath(), $locale); - if (!$newRoute) { - return null; - } - - $oldRoute = $this->routeRepository->findByEntity(\get_class($document), $document->getUuid(), $locale); - $history = $this->routeRepository->findHistoryByEntity(\get_class($document), $document->getUuid(), $locale); - - /** @var RouteInterface $historyRoute */ - foreach (\array_filter(\array_merge($history, [$oldRoute])) as $historyRoute) { - if ($historyRoute->getId() === $newRoute->getId() || $document->getId() !== $historyRoute->getEntityId()) { - // Mismatch of entity-id's happens because doctrine don't check entities which has been changed in the - // current session. If the old-route was already reused by a page before it will be returned in the - // query of line 329. - - continue; - } - - $historyRoute->setTarget($newRoute); - $historyRoute->setHistory(true); - $newRoute->addHistory($historyRoute); - } - - $newRoute->setEntityClass(\get_class($document)); - $newRoute->setEntityId($document->getId()); - $newRoute->setTarget(null); - $newRoute->setHistory(false); - - return $newRoute; - } - - private function updateRoute(RoutablePageBehavior $document): void - { - $locale = $this->documentInspector->getLocale($document); - $propertyName = $this->getRoutePathPropertyName((string) $document->getStructureType(), $locale); - - $route = $this->chainRouteGenerator->generate($document); - $document->setRoutePath($route->getPath()); - - $node = $this->documentInspector->getNode($document); - $node->setProperty($propertyName, $route->getPath()); - $node->setProperty($this->propertyEncoder->localizedContentName(self::ROUTE_FIELD_NAME, (string) $locale), $propertyName); - } - - private function updateChildRoutes(ChildrenBehavior $document): void - { - foreach ($document->getChildren() as $childDocument) { - if (!$childDocument instanceof RoutablePageBehavior) { - continue; - } - - $this->updateRoute($childDocument); - } - } - - /** - * Generates child routes. - * - * @return string[] - */ - private function generateChildRoutes(ChildrenBehavior $document, string $locale): array - { - $routes = []; - foreach ($document->getChildren() as $child) { - if (!$child instanceof RoutablePageBehavior) { - continue; - } - - $childRoute = $this->createOrUpdatePageRoute($child, $locale); - $this->entityManager->persist($childRoute); - - $child->setRoutePath($childRoute->getPath()); - $childNode = $this->documentInspector->getNode($child); - - $propertyName = $this->getRoutePathPropertyName((string) $child->getStructureType(), $locale); - $childNode->setProperty($propertyName, $childRoute->getPath()); - - $routes[] = $childRoute->getPath(); - } - - return $routes; - } - - /** - * Removes old-routes where the node does not exists anymore. - */ - private function removeOldChildRoutes(SessionInterface $session, array $oldRoutes, string $locale): void - { - foreach ($oldRoutes as $oldRoute) { - $oldRouteEntity = $this->routeRepository->findByPath($oldRoute, $locale); - if ($oldRouteEntity && !$this->nodeExists($session, $oldRouteEntity->getEntityId())) { - $this->entityManager->remove($oldRouteEntity); - } - } - - $this->entityManager->flush(); - } - - /** - * Iterate over children and remove routes. - */ - private function removeChildRoutes(ChildrenBehavior $document, string $locale): void - { - foreach ($document->getChildren() as $child) { - if ($child instanceof RoutablePageBehavior) { - $this->removeChildRoute($child, $locale); - } - - if ($child instanceof ChildrenBehavior) { - $this->removeChildRoutes($child, $locale); - } - } - } - - /** - * Removes route if exists. - */ - private function removeChildRoute(RoutablePageBehavior $document, string $locale): void - { - $route = $this->routeRepository->findByPath($document->getRoutePath(), $locale); - if ($route) { - $this->entityManager->remove($route); - } - } - - /** - * Returns encoded "routePath" property-name. - */ - private function getRoutePathPropertyName(string $structureType, string $locale): string - { - $metadata = $this->metadataFactory->getStructureMetadata('article', $structureType); - - if ($metadata->hasTag(self::TAG_NAME)) { - return $this->getPropertyName($locale, $metadata->getPropertyByTagName(self::TAG_NAME)->getName()); - } - - return $this->getPropertyName($locale, self::ROUTE_FIELD); - } - - /** - * Returns encoded property-name. - */ - private function getPropertyName(string $locale, string $field): string - { - return $this->propertyEncoder->localizedSystemName($field, $locale); - } - - /** - * Returns true if given uuid exists. - */ - private function nodeExists(SessionInterface $session, string $uuid): bool - { - try { - $session->getNodeByIdentifier($uuid); - - return true; - } catch (ItemNotFoundException $exception) { - return false; - } - } -} diff --git a/Document/Subscriber/WebspaceSubscriber.php b/Document/Subscriber/WebspaceSubscriber.php deleted file mode 100644 index 5bb8d23b9..000000000 --- a/Document/Subscriber/WebspaceSubscriber.php +++ /dev/null @@ -1,154 +0,0 @@ -documentManager = $documentManager; - $this->documentInspector = $documentInspector; - $this->propertyEncoder = $propertyEncoder; - } - - public static function getSubscribedEvents() - { - return [ - Events::HYDRATE => ['loadProperties'], - Events::PERSIST => ['saveProperties'], - Events::PUBLISH => ['saveProperties'], - ]; - } - - public function loadProperties(AbstractMappingEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof WebspaceBehavior) { - return; - } - - $locale = $event->getLocale(); - if (LocalizationState::GHOST === $this->documentInspector->getLocalizationState($document)) { - $locale = $document->getOriginalLocale(); - } - - $mainWebspace = $event->getNode()->getPropertyValueWithDefault( - $this->getMainWebspacePropertyName($locale), - null - ); - $additionalWebspaces = $event->getNode()->getPropertyValueWithDefault( - $this->getAdditionalWebspacesPropertyName($locale), - null - ); - - $document->setMainWebspace($mainWebspace); - $document->setAdditionalWebspaces($additionalWebspaces); - } - - public function saveProperties(AbstractMappingEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleInterface || !$document instanceof WebspaceBehavior) { - return; - } - - $parentPageUuid = $this->getParentPageUuidFromPageTree($document); - if ($parentPageUuid) { - // we know now it's a `page_tree_route` route - // so load the parent and find out the webspace - try { - $parentDocument = $this->documentManager->find($parentPageUuid, $event->getLocale()); - $mainWebspace = $this->documentInspector->getWebspace($parentDocument); - $document->setMainWebspace($mainWebspace); - $document->setAdditionalWebspaces([]); - } catch (DocumentNotFoundException $exception) { - // Do nothing, because when the parent page was deleted it should still work while restoring. - } - } - - $mainWebspace = $document->getMainWebspace(); - $additionalWebspaces = null; - if ($mainWebspace) { - $mainWebspace = $document->getMainWebspace(); - $additionalWebspaces = $document->getAdditionalWebspaces(); - } - - $event->getNode()->setProperty( - $this->getMainWebspacePropertyName($document->getLocale()), - $mainWebspace - ); - $event->getNode()->setProperty( - $this->getAdditionalWebspacesPropertyName($document->getLocale()), - $additionalWebspaces - ); - } - - /** - * Returns encoded "mainWebspace" property-name. - */ - private function getMainWebspacePropertyName(string $locale): string - { - return $this->propertyEncoder->localizedSystemName(self::MAIN_WEBSPACE_PROPERTY, $locale); - } - - /** - * Returns encoded "additionalWebspaces" property-name. - */ - private function getAdditionalWebspacesPropertyName(string $locale): string - { - return $this->propertyEncoder->localizedSystemName(self::ADDITIONAL_WEBSPACES_PROPERTY, $locale); - } - - protected function getDocumentInspector() - { - return $this->documentInspector; - } -} diff --git a/Document/TagViewObject.php b/Document/TagViewObject.php deleted file mode 100644 index 18df5e713..000000000 --- a/Document/TagViewObject.php +++ /dev/null @@ -1,45 +0,0 @@ -articleDocument = $articleDocument; - $this->sourceArticleId = $sourceArticleId; - $this->sourceArticleTitle = $sourceArticleTitle; - $this->sourceArticleTitleLocale = $sourceArticleTitleLocale; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'copied'; - } - - public function getEventContext(): array - { - return [ - 'sourceArticleId' => $this->sourceArticleId, - 'sourceArticleTitle' => $this->sourceArticleTitle, - 'sourceArticleTitleLocale' => $this->sourceArticleTitleLocale, - ]; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleCreatedEvent.php b/Domain/Event/ArticleCreatedEvent.php deleted file mode 100644 index 9db716b07..000000000 --- a/Domain/Event/ArticleCreatedEvent.php +++ /dev/null @@ -1,91 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - $this->payload = $payload; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'created'; - } - - public function getEventPayload(): ?array - { - return $this->payload; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleDraftRemovedEvent.php b/Domain/Event/ArticleDraftRemovedEvent.php deleted file mode 100644 index d5378ee6e..000000000 --- a/Domain/Event/ArticleDraftRemovedEvent.php +++ /dev/null @@ -1,81 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'draft_removed'; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleModifiedEvent.php b/Domain/Event/ArticleModifiedEvent.php deleted file mode 100644 index 9ca7c15fc..000000000 --- a/Domain/Event/ArticleModifiedEvent.php +++ /dev/null @@ -1,91 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - $this->payload = $payload; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'modified'; - } - - public function getEventPayload(): ?array - { - return $this->payload; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticlePublishedEvent.php b/Domain/Event/ArticlePublishedEvent.php deleted file mode 100644 index af96beab9..000000000 --- a/Domain/Event/ArticlePublishedEvent.php +++ /dev/null @@ -1,81 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'published'; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleRemovedEvent.php b/Domain/Event/ArticleRemovedEvent.php deleted file mode 100644 index b207ac22f..000000000 --- a/Domain/Event/ArticleRemovedEvent.php +++ /dev/null @@ -1,73 +0,0 @@ -articleId = $articleId; - $this->articleTitle = $articleTitle; - $this->articleTitleLocale = $articleTitleLocale; - } - - public function getEventType(): string - { - return 'removed'; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return $this->articleId; - } - - public function getResourceTitle(): ?string - { - return $this->articleTitle; - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleTitleLocale; - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleRestoredEvent.php b/Domain/Event/ArticleRestoredEvent.php deleted file mode 100644 index 91775bfe8..000000000 --- a/Domain/Event/ArticleRestoredEvent.php +++ /dev/null @@ -1,80 +0,0 @@ -articleDocument = $articleDocument; - $this->payload = $payload; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'restored'; - } - - public function getEventPayload(): ?array - { - return $this->payload; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleTranslationAddedEvent.php b/Domain/Event/ArticleTranslationAddedEvent.php deleted file mode 100644 index 697940421..000000000 --- a/Domain/Event/ArticleTranslationAddedEvent.php +++ /dev/null @@ -1,94 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - $this->payload = $payload; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'translation_added'; - } - - public function getEventPayload(): ?array - { - return $this->payload; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleTranslationCopiedEvent.php b/Domain/Event/ArticleTranslationCopiedEvent.php deleted file mode 100644 index 309e717ff..000000000 --- a/Domain/Event/ArticleTranslationCopiedEvent.php +++ /dev/null @@ -1,108 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - $this->sourceLocale = $sourceLocale; - $this->payload = $payload; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'translation_copied'; - } - - public function getEventContext(): array - { - return [ - 'sourceLocale' => $this->sourceLocale, - ]; - } - - public function getEventPayload(): ?array - { - return $this->payload; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleTranslationRemovedEvent.php b/Domain/Event/ArticleTranslationRemovedEvent.php deleted file mode 100644 index 4a1ff580c..000000000 --- a/Domain/Event/ArticleTranslationRemovedEvent.php +++ /dev/null @@ -1,79 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'translation_removed'; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleTranslationRestoredEvent.php b/Domain/Event/ArticleTranslationRestoredEvent.php deleted file mode 100644 index 44922f811..000000000 --- a/Domain/Event/ArticleTranslationRestoredEvent.php +++ /dev/null @@ -1,94 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - $this->payload = $payload; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'translation_restored'; - } - - public function getEventPayload(): ?array - { - return $this->payload; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } -} diff --git a/Domain/Event/ArticleUnpublishedEvent.php b/Domain/Event/ArticleUnpublishedEvent.php deleted file mode 100644 index 79df54bf3..000000000 --- a/Domain/Event/ArticleUnpublishedEvent.php +++ /dev/null @@ -1,87 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'unpublished'; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return (string) $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } - - public function getResourceSecurityObjectType(): ?string - { - return SecurityBehavior::class; - } -} diff --git a/Domain/Event/ArticleVersionRestoredEvent.php b/Domain/Event/ArticleVersionRestoredEvent.php deleted file mode 100644 index 12a8f6ba5..000000000 --- a/Domain/Event/ArticleVersionRestoredEvent.php +++ /dev/null @@ -1,101 +0,0 @@ -articleDocument = $articleDocument; - $this->locale = $locale; - $this->version = $version; - } - - public function getArticleDocument(): ArticleDocument - { - return $this->articleDocument; - } - - public function getEventType(): string - { - return 'version_restored'; - } - - public function getEventContext(): array - { - return [ - 'version' => $this->version, - ]; - } - - public function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getResourceId(): string - { - return $this->articleDocument->getUuid(); - } - - public function getResourceLocale(): ?string - { - return $this->locale; - } - - public function getResourceTitle(): ?string - { - return $this->articleDocument->getTitle(); - } - - public function getResourceTitleLocale(): ?string - { - return $this->articleDocument->getLocale(); - } - - public function getResourceSecurityContext(): ?string - { - return ArticleAdmin::SECURITY_CONTEXT; - } - - public function getResourceSecurityObjectType(): ?string - { - return SecurityBehavior::class; - } -} diff --git a/Elasticsearch/AnnotationReader.php b/Elasticsearch/AnnotationReader.php deleted file mode 100644 index 00cd9411f..000000000 --- a/Elasticsearch/AnnotationReader.php +++ /dev/null @@ -1,72 +0,0 @@ -inner = $inner; - $this->articleViewDocumentClass = $articleViewDocumentClass; - } - - public function getClassAnnotations(\ReflectionClass $class) - { - return $this->inner->getClassAnnotations($class); - } - - public function getClassAnnotation(\ReflectionClass $class, $annotationName) - { - $result = $this->inner->getClassAnnotation($class, $annotationName); - if (!$result && Document::class === $annotationName && $class->getName() === $this->articleViewDocumentClass) { - $annotation = new Document(); - $annotation->type = 'article'; - - return $annotation; - } - - return $result; - } - - public function getMethodAnnotations(\ReflectionMethod $method) - { - return $this->inner->getMethodAnnotations($method); - } - - public function getMethodAnnotation(\ReflectionMethod $method, $annotationName) - { - return $this->inner->getMethodAnnotation($method, $annotationName); - } - - public function getPropertyAnnotations(\ReflectionProperty $property) - { - return $this->inner->getPropertyAnnotations($property); - } - - public function getPropertyAnnotation(\ReflectionProperty $property, $annotationName) - { - return $this->inner->getPropertyAnnotation($property, $annotationName); - } -} diff --git a/Elasticsearch/EventAwareConverter.php b/Elasticsearch/EventAwareConverter.php deleted file mode 100644 index d088f73bc..000000000 --- a/Elasticsearch/EventAwareConverter.php +++ /dev/null @@ -1,43 +0,0 @@ -dispatcher = $dispatcher; - } - - public function convertToDocument($rawData, Manager $manager) - { - $document = parent::convertToDocument($rawData, $manager); - $this->dispatcher->dispatch(new PostConvertToDocumentEvent($rawData, $document, $manager), PostConvertToDocumentEvent::NAME); - - return $document; - } -} diff --git a/Elasticsearch/PostConvertToDocumentEvent.php b/Elasticsearch/PostConvertToDocumentEvent.php deleted file mode 100644 index 1efb36c90..000000000 --- a/Elasticsearch/PostConvertToDocumentEvent.php +++ /dev/null @@ -1,69 +0,0 @@ -rawData = $rawData; - $this->document = $document; - $this->manager = $manager; - } - - /** - * Returns rawData. - */ - public function getRawData(): array - { - return $this->rawData; - } - - /** - * Returns document. - */ - public function getDocument(): object - { - return $this->document; - } - - /** - * Returns manager. - */ - public function getManager(): Manager - { - return $this->manager; - } -} diff --git a/Event/IndexEvent.php b/Event/IndexEvent.php deleted file mode 100644 index b4c510352..000000000 --- a/Event/IndexEvent.php +++ /dev/null @@ -1,56 +0,0 @@ -document = $document; - $this->viewDocument = $viewDocument; - } - - /** - * Returns article. - */ - public function getDocument(): ArticleDocument - { - return $this->document; - } - - /** - * Returns view-document. - */ - public function getViewDocument(): ArticleViewDocumentInterface - { - return $this->viewDocument; - } -} diff --git a/EventListener/ArticleTrashSubscriber.php b/EventListener/ArticleTrashSubscriber.php deleted file mode 100644 index c79fc9f9e..000000000 --- a/EventListener/ArticleTrashSubscriber.php +++ /dev/null @@ -1,109 +0,0 @@ -trashManager = $trashManager; - $this->entityManager = $entityManager; - } - - /** - * @return array - */ - public static function getSubscribedEvents(): array - { - return [ - Events::REMOVE => ['storeArticleToTrash', 1024], - Events::REMOVE_LOCALE => ['storeArticleTranslationToTrash', 1024], - Events::FLUSH => 'flushTrashItem', - Events::CLEAR => 'clearPendingTrashItem', - ]; - } - - public function storeArticleToTrash(RemoveEvent $event): void - { - $document = $event->getDocument(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->trashManager->store(ArticleDocument::RESOURCE_KEY, $document); - $this->hasPendingTrashItem = true; - } - - public function storeArticleTranslationToTrash(RemoveLocaleEvent $event): void - { - $document = $event->getDocument(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->trashManager->store( - ArticleDocument::RESOURCE_KEY, - $document, - ['locale' => $event->getLocale()] - ); - $this->hasPendingTrashItem = true; - } - - public function flushTrashItem(FlushEvent $event): void - { - if (!$this->hasPendingTrashItem) { - return; - } - - $this->entityManager->flush(); - $this->hasPendingTrashItem = false; - } - - public function clearPendingTrashItem(ClearEvent $event): void - { - $this->hasPendingTrashItem = false; - } -} diff --git a/EventListener/ContentProxyListener.php b/EventListener/ContentProxyListener.php deleted file mode 100644 index f39e71d8e..000000000 --- a/EventListener/ContentProxyListener.php +++ /dev/null @@ -1,84 +0,0 @@ -contentProxyFactory = $contentProxyFactory; - $this->structureManager = $structureManager; - } - - /** - * Add the proxies for content and view to view-documents. - */ - public function onPostConvertToDocument(PostConvertToDocumentEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleViewDocumentInterface) { - return; - } - - $structure = $this->structureManager->getStructure($document->getStructureType(), 'article'); - - if (!$structure) { - throw new \RuntimeException(\sprintf('Could not find article structure from type "%s".', $document->getStructureType())); - } - - $structure->setUuid($document->getUuid()); - $structure->setLanguageCode($document->getLocale()); - - list($content, $view) = $this->getProxies($document->getContentData(), $structure); - - $document->setContent($content); - $document->setView($view); - - foreach ($document->getPages() as $page) { - $structure->setUuid($page->uuid); - list($page->content, $page->view) = $this->getProxies($page->contentData, $structure); - } - } - - /** - * Create content and view proxy for given content-data. - */ - private function getProxies(string $contentData, StructureInterface $structure): array - { - $contentData = $contentData ?: '{}'; - $data = \json_decode($contentData, true); - - $content = $this->contentProxyFactory->createContentProxy($structure, $data); - $view = $this->contentProxyFactory->createViewProxy($structure, $data); - - return [$content, $view]; - } -} diff --git a/EventListener/DomainEventSubscriber.php b/EventListener/DomainEventSubscriber.php deleted file mode 100644 index 11d17788d..000000000 --- a/EventListener/DomainEventSubscriber.php +++ /dev/null @@ -1,429 +0,0 @@ -> - */ - private $eventsToBeDispatchedAfterFlush = []; - - /** - * @var array - */ - private $persistEventsWithNewDocument = []; - - /** - * @var array - */ - private $persistEventsWithNewLocale = []; - - public function __construct( - DocumentDomainEventCollectorInterface $domainEventCollector, - DocumentManagerInterface $documentManager, - PropertyEncoder $propertyEncoder - ) { - $this->domainEventCollector = $domainEventCollector; - $this->documentManager = $documentManager; - $this->propertyEncoder = $propertyEncoder; - } - - /** - * @return array - */ - public static function getSubscribedEvents(): array - { - return [ - Events::FLUSH => 'handleFlush', - Events::PERSIST => [ - ['handlePrePersist', 479], // Priority needs to be lower than AutoNameSubscriber::handlePersist (480) - ['handlePersist', -10000], - ], - Events::REMOVE => ['handleRemove', -10000], - Events::REMOVE_LOCALE => ['handleRemoveLocale', -10000], - Events::COPY_LOCALE => ['handleCopyLocale', -10000], - Events::COPY => ['handleCopy', -10000], - Events::PUBLISH => ['handlePublish', -10000], - Events::UNPUBLISH => ['handleUnpublish', -10000], - Events::REMOVE_DRAFT => ['handleRemoveDraft', -10000], - Events::RESTORE => ['handleRestore', -10000], - ]; - } - - public function handleFlush(FlushEvent $event): void - { - $eventsToBeDispatched = $this->eventsToBeDispatchedAfterFlush; - - if (0 === \count($eventsToBeDispatched)) { - return; - } - - $this->eventsToBeDispatchedAfterFlush = []; - - foreach ($eventsToBeDispatched as $eventConfig) { - $type = $eventConfig['type'] ?? null; - $options = $eventConfig['options'] ?? []; - - switch ($type) { - case ArticleCopiedEvent::class: - $articlePath = $options['articlePath'] ?? null; - Assert::notNull($articlePath); - $locale = $options['locale'] ?? null; - Assert::notNull($locale); - $sourceArticleId = $options['sourceArticleId'] ?? null; - Assert::notNull($sourceArticleId); - $sourceArticleTitle = $options['sourceArticleTitle'] ?? null; - Assert::notNull($sourceArticleTitle); - - /** @var ArticleDocument $document */ - $document = $this->documentManager->find($articlePath, $locale); - - $this->domainEventCollector->collect( - new ArticleCopiedEvent( - $document, - $sourceArticleId, - $sourceArticleTitle, - $locale - ) - ); - - $this->documentManager->flush(); - - break; - } - } - } - - public function handlePrePersist(PersistEvent $event): void - { - if (!$event->hasNode()) { - return; - } - - /** @var string|null $locale */ - $locale = $event->getLocale(); - $node = $event->getNode(); - - if (null === $locale) { - return; - } - - $eventHash = \spl_object_hash($event); - - if ($this->isNewNode($node)) { - $this->persistEventsWithNewDocument[$eventHash] = true; - - return; - } - - if ($this->isNewTranslation($node, $locale)) { - $this->persistEventsWithNewLocale[$eventHash] = true; - } - } - - public function handlePersist(PersistEvent $event): void - { - if (true === $event->getOption('omit_modified_domain_event')) { - return; - } - - /** @var string|null $locale */ - $locale = $event->getLocale(); - $document = $event->getDocument(); - - if (null === $locale || !$document instanceof ArticleDocument) { - return; - } - - $payload = $this->getPayloadFromArticleDocument($document); - - $eventHash = \spl_object_hash($event); - - if (true === ($this->persistEventsWithNewDocument[$eventHash] ?? null)) { - unset($this->persistEventsWithNewDocument[$eventHash]); - - $this->domainEventCollector->collect( - new ArticleCreatedEvent($document, $locale, $payload) - ); - - return; - } - - if (true === ($this->persistEventsWithNewLocale[$eventHash] ?? null)) { - unset($this->persistEventsWithNewLocale[$eventHash]); - - $this->domainEventCollector->collect( - new ArticleTranslationAddedEvent($document, $locale, $payload) - ); - - return; - } - - $this->domainEventCollector->collect( - new ArticleModifiedEvent($document, $locale, $payload) - ); - } - - public function handleRemove(RemoveEvent $event): void - { - $document = $event->getDocument(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->domainEventCollector->collect( - new ArticleRemovedEvent( - $document->getUuid(), - $document->getTitle(), - $document->getLocale() - ) - ); - } - - public function handleRemoveLocale(RemoveLocaleEvent $event): void - { - $document = $event->getDocument(); - $locale = $event->getLocale(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->domainEventCollector->collect( - new ArticleTranslationRemovedEvent( - $document, - $locale - ) - ); - } - - public function handleCopyLocale(CopyLocaleEvent $event): void - { - $document = $event->getDocument(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $destDocument = $event->getDestDocument(); - - if (!$destDocument instanceof ArticleDocument) { - return; - } - - $destLocale = $event->getDestLocale(); - $sourceLocale = $event->getLocale(); - $payload = $this->getPayloadFromArticleDocument($destDocument); - - $this->domainEventCollector->collect( - new ArticleTranslationCopiedEvent( - $destDocument, - $destLocale, - $sourceLocale, - $payload - ) - ); - } - - public function handleCopy(CopyEvent $event): void - { - $document = $event->getDocument(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->eventsToBeDispatchedAfterFlush[] = [ - 'type' => ArticleCopiedEvent::class, - 'options' => [ - 'articlePath' => $event->getCopiedPath(), - 'locale' => $document->getLocale(), - 'sourceArticleId' => $document->getUuid(), - 'sourceArticleTitle' => $document->getTitle(), - ], - ]; - } - - public function handlePublish(PublishEvent $event): void - { - $document = $event->getDocument(); - $locale = $event->getLocale(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->domainEventCollector->collect( - new ArticlePublishedEvent( - $document, - $locale - ) - ); - } - - public function handleUnpublish(UnpublishEvent $event): void - { - $document = $event->getDocument(); - $locale = $event->getLocale(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->domainEventCollector->collect( - new ArticleUnpublishedEvent( - $document, - $locale - ) - ); - } - - public function handleRemoveDraft(RemoveDraftEvent $event): void - { - $document = $event->getDocument(); - $locale = $event->getLocale(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->domainEventCollector->collect( - new ArticleDraftRemovedEvent( - $document, - $locale - ) - ); - } - - public function handleRestore(RestoreEvent $event): void - { - $document = $event->getDocument(); - $locale = $event->getLocale(); - $version = $event->getVersion(); - - if (!$document instanceof ArticleDocument) { - return; - } - - $this->domainEventCollector->collect( - new ArticleVersionRestoredEvent( - $document, - $locale, - $version - ) - ); - } - - /** - * @return mixed[] - */ - private function getPayloadFromArticleDocument(ArticleDocument $articleDocument): array - { - $data = $articleDocument->getStructure()->toArray(); - - /** @var ExtensionContainer|mixed[] $extensionData */ - $extensionData = $articleDocument->getExtensionsData(); - - if ($extensionData instanceof ExtensionContainer) { - $extensionData = $extensionData->toArray(); - } - - $data['ext'] = $extensionData; - - return $data; - } - - /** - * @param NodeInterface $node - * - * @see SecuritySubscriber::handlePersistCreate() - */ - private function isNewNode(NodeInterface $node): bool - { - /** @var \Countable $properties */ - $properties = $node->getProperties( - $this->propertyEncoder->encode( - 'system_localized', - StructureSubscriber::STRUCTURE_TYPE_FIELD, - '*' - ) - ); - - return 0 === \count($properties); - } - - /** - * @param NodeInterface $node - */ - private function isNewTranslation(NodeInterface $node, string $locale): bool - { - /** @var \Countable $localizedProperties */ - $localizedProperties = $node->getProperties( - $this->propertyEncoder->localizedContentName('*', $locale) - ); - - return 0 === \count($localizedProperties); - } -} diff --git a/EventListener/TargetWebspaceListener.php b/EventListener/TargetWebspaceListener.php deleted file mode 100644 index 05f1a3e32..000000000 --- a/EventListener/TargetWebspaceListener.php +++ /dev/null @@ -1,62 +0,0 @@ -requestAnalyzer = $requestAnalyzer; - } - - /** - * Add the proxies for content and view to view-documents. - */ - public function onPostConvertToDocument(PostConvertToDocumentEvent $event): void - { - $document = $event->getDocument(); - if (!$document instanceof ArticleViewDocumentInterface) { - return; - } - - $document->setTargetWebspace($this->getTargetWebspace($document)); - } - - private function getTargetWebspace(ArticleViewDocumentInterface $document): ?string - { - if (!$this->requestAnalyzer->getWebspace()) { - return null; - } - - $webspaceKey = $this->requestAnalyzer->getWebspace()->getKey(); - - if ($document->getMainWebspace() === $webspaceKey - || ($document->getAdditionalWebspaces() && \in_array($webspaceKey, $document->getAdditionalWebspaces())) - ) { - return $webspaceKey; - } - - return $document->getMainWebspace(); - } -} diff --git a/Exception/ArticleInRequestNotFoundException.php b/Exception/ArticleInRequestNotFoundException.php deleted file mode 100644 index 7aa963baf..000000000 --- a/Exception/ArticleInRequestNotFoundException.php +++ /dev/null @@ -1,23 +0,0 @@ -pageUuid = $pageUuid; - $this->articleUuid = $articleUuid; - } - - /** - * Returns page-uuid. - */ - public function getPageUuid(): string - { - return $this->pageUuid; - } - - /** - * Returns article-uuid. - */ - public function getArticleUuid(): string - { - return $this->articleUuid; - } -} diff --git a/Exception/ParameterNotAllowedException.php b/Exception/ParameterNotAllowedException.php deleted file mode 100644 index 9487e258c..000000000 --- a/Exception/ParameterNotAllowedException.php +++ /dev/null @@ -1,52 +0,0 @@ -property = $property; - $this->class = $class; - } - - /** - * Returns property. - */ - public function getProperty(): string - { - return $this->property; - } - - /** - * Returns class. - */ - public function getClass(): string - { - return $this->class; - } -} diff --git a/Exception/RouteSchemaNotFoundException.php b/Exception/RouteSchemaNotFoundException.php deleted file mode 100644 index d962685ca..000000000 --- a/Exception/RouteSchemaNotFoundException.php +++ /dev/null @@ -1,59 +0,0 @@ -requested = $requested; - $this->available = $available; - } - - /** - * Returns requested. - */ - public function getRequested(): string - { - return $this->requested; - } - - /** - * Returns requested. - * - * @return string[] - */ - public function getAvailable(): array - { - return $this->available; - } -} diff --git a/Export/ArticleExport.php b/Export/ArticleExport.php deleted file mode 100644 index 3cbdab16a..000000000 --- a/Export/ArticleExport.php +++ /dev/null @@ -1,216 +0,0 @@ -structureManager = $structureManager; - $this->extensionManager = $extensionManager; - } - - public function export(string $locale, string $format = '1.2.xliff', ?OutputInterface $output = null): string - { - $this->exportLocale = $locale; - $this->format = $format; - $this->output = $output; - - if (!$this->output) { - $this->output = new NullOutput(); - } - - $this->output->writeln('Loading Data…'); - - $exportData = $this->getExportData($locale); - - $this->output->writeln([ - '', - 'Render Xliff…', - ]); - - return $this->templating->render( - $this->getTemplate($this->format), - $exportData - ); - } - - public function getExportData(string $locale): array - { - /** @var ArticleDocument[] $documents */ - $documents = $this->getDocuments($locale); - - $progress = new ProgressBar($this->output, \count($documents)); - $progress->start(); - - $documentData = []; - foreach ($documents as $key => $document) { - $contentData = $this->getContentData($document, $this->exportLocale); - $extensionData = $this->getExtensionData($document); - $settingData = $this->getSettingData($document); - - $documentData[] = [ - 'uuid' => $document->getUuid(), - 'locale' => $document->getLocale(), - 'content' => $contentData, - 'settings' => $settingData, - 'extensions' => $extensionData, - ]; - - $progress->advance(); - } - - $progress->finish(); - - return [ - 'locale' => $locale, - 'format' => $this->format, - 'documents' => $documentData, - ]; - } - - protected function getExtensionData(ArticleDocument $document): array - { - $data = $document->getExtensionsData(); - if ($data instanceof ExtensionContainer) { - $data = $data->toArray(); - } - - $extensionData = []; - foreach ($data as $extensionName => $extensionProperties) { - /** @var ExcerptStructureExtension $extension */ - $extension = $this->extensionManager->getExtension($document->getStructureType(), $extensionName); - - if ($extension instanceof ExportExtensionInterface) { - $extensionData[$extensionName] = $extension->export($extensionProperties, $this->format); - } - } - - return $extensionData; - } - - protected function getSettingData(ArticleDocument $document): array - { - if ($created = $document->getCreated()) { - $created = $created->format('c'); - } - - if ($changed = $document->getChanged()) { - $changed = $changed->format('c'); - } - - if ($published = $document->getPublished()) { - $published = $published->format('c'); - } - - if (($authored = $document->getAuthored()) && $authored instanceof \DateTime) { - $authored = $authored->format('c'); - } - - $settingOptions = []; - if ('1.2.xliff' === $this->format) { - $settingOptions = ['translate' => false]; - } - - return [ - 'structureType' => $this->createProperty('structureType', $document->getStructureType(), $settingOptions), - 'published' => $this->createProperty('published', $published, $settingOptions), - 'created' => $this->createProperty('created', $created, $settingOptions), - 'changed' => $this->createProperty('changed', $changed, $settingOptions), - 'creator' => $this->createProperty('creator', $document->getCreator(), $settingOptions), - 'changer' => $this->createProperty('changer', $document->getChanger(), $settingOptions), - 'locale' => $this->createProperty('locale', $document->getLocale(), $settingOptions), - 'shadowLocale' => $this->createProperty('shadowLocale', $document->getShadowLocale(), $settingOptions), - 'originalLocale' => $this->createProperty('originalLocale', $document->getOriginalLocale(), $settingOptions), - 'routePath' => $this->createProperty('routePath', $document->getRoutePath(), $settingOptions), - 'workflowStage' => $this->createProperty('workflowStage', $document->getWorkflowStage(), $settingOptions), - 'path' => $this->createProperty('path', $document->getPath(), $settingOptions), - 'mainWebspace' => $this->createProperty('mainWebspace', $document->getMainWebspace(), $settingOptions), - 'additionalWebspaces' => $this->createProperty('additionalWebspaces', \json_encode($document->getAdditionalWebspaces()), $settingOptions), - 'author' => $this->createProperty('author', $document->getAuthor(), $settingOptions), - 'authored' => $this->createProperty('authored', $authored, $settingOptions), - ]; - } - - protected function getDocuments(string $locale): QueryResultCollection - { - $where = []; - - // only articles - $where[] = '[jcr:mixinTypes] = "sulu:article"'; - - // filter by path - $where[] = 'ISDESCENDANTNODE("/cmf/articles")'; - - // do not load ghost articles - $where[] = \sprintf( - '[i18n:%s-template] IS NOT NULL', - $locale - ); - - $query = $this->documentManager->createQuery( - 'SELECT * FROM [nt:unstructured] AS a WHERE ' . \implode(' AND ', $where), - $locale - ); - - return $query->execute(); - } - - protected function getTemplate($format) - { - if (!isset($this->formatFilePaths[$format])) { - throw new ExportFormatNotFoundException(\sprintf('No format "%s" configured for Snippet export', $format)); - } - - return $this->formatFilePaths[$format]; - } -} diff --git a/Export/ArticleExportInterface.php b/Export/ArticleExportInterface.php deleted file mode 100644 index d91b3c194..000000000 --- a/Export/ArticleExportInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -format = $format; - } - - public function getFormat(): string - { - return $this->format; - } -} diff --git a/Import/ArticleImport.php b/Import/ArticleImport.php deleted file mode 100644 index f3ddee701..000000000 --- a/Import/ArticleImport.php +++ /dev/null @@ -1,338 +0,0 @@ - $xliff12]); - - $this->documentManager = $documentManager; - $this->documentInspector = $documentInspector; - $this->documentRegistry = $documentRegistry; - $this->structureManager = $structureManager; - $this->extensionManager = $extensionManager; - $this->logger = $logger ?: new NullLogger(); - } - - public function import( - string $locale, - string $filePath, - ?OutputInterface $output = null, - string $format = '1.2.xliff', - bool $overrideSettings = false - ): ImportResult { - $parsedDataList = $this->getParser($format)->parse($filePath, $locale); - $failedImports = []; - $importedCounter = 0; - $successCounter = 0; - - if (null === $output) { - $output = new NullOutput(); - } - - $progress = new ProgressBar($output, \count($parsedDataList)); - $progress->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%'); - $progress->start(); - - foreach ($parsedDataList as $parsedData) { - ++$importedCounter; - - try { - $this->importDocument($parsedData, $format, $locale, $overrideSettings); - ++$successCounter; - } catch (ImportException $exception) { - $failedImports[] = $parsedData; - } - - $this->logger->info(\sprintf('Document %s/%s', $importedCounter, \count($parsedDataList))); - - $progress->advance(); - } - - $progress->finish(); - - return new ImportResult($importedCounter, \count($failedImports), $successCounter, $failedImports, $this->exceptionStore); - } - - protected function importDocument(array $parsedData, string $format, string $locale, bool $overrideSettings): void - { - $uuid = null; - - try { - if (!isset($parsedData['uuid']) || !isset($parsedData['structureType']) || !isset($parsedData['data'])) { - $this->addException('uuid, structureType or data for import not found.', 'ignore'); - - throw new ImportException('uuid, structureType or data for import not found.'); - } - - $uuid = $parsedData['uuid']; - $structureType = $parsedData['structureType']; - $data = $parsedData['data']; - - /** @var ArticleDocument $document */ - $document = $this->documentManager->find( - $uuid, - $locale, - [ - 'load_ghost_content' => false, - ] - ); - - if (!$document instanceof ArticleDocument) { - throw new ImportException(\sprintf('Document(%s) is not an instanecof BasePageDocument', $uuid)); - } - - $document->setStructureType($structureType); - - if (!$this->setDocumentData($document, $locale, $format, $data)) { - throw new ImportException(); - } - - $this->setDocumentSettings($document, $format, $data, $overrideSettings); - - // save document - $this->documentManager->persist($document, $locale); - - if (WorkflowStage::PUBLISHED === ((int) $this->getParser($format)->getPropertyData('workflowStage', $data))) { - $this->documentManager->publish($document, $locale); - } - - $this->documentManager->flush(); - $this->documentRegistry->clear(); - } catch (\Exception $e) { - if ($e instanceof DocumentManagerException) { - throw new ImportException('', 0, $e); - } - - $this->logger->error( - \sprintf( - '%s%s: %s%s', - $uuid, - \PHP_EOL . \get_class($e), - $e->getMessage(), - \PHP_EOL . $e->getTraceAsString() - ) - ); - - $this->documentManager->flush(); - $this->documentManager->clear(); - - throw new ImportException('', 0, $e); - } - } - - protected function setDocumentData( - ArticleDocument $document, - string $locale, - string $format, - array $data - ): bool { - /** @var ArticleBridge $structure */ - $structure = $this->structureManager->getStructure($document->getStructureType(), 'article'); - $node = $this->documentRegistry->getNodeForDocument($document); - $node->setProperty(\sprintf('i18n:%s-template', $locale), $document->getStructureType()); - $state = $this->getParser($format)->getPropertyData('state', $data, null, null, 2); - $node->setProperty(\sprintf('i18n:%s-state', $locale), $state); - - if ('' === $this->getParser($format)->getPropertyData('title', $data)) { - $this->addException(\sprintf('Document(%s) has not set any title', $document->getUuid()), 'ignore'); - - return false; - } - - $structure->setDocument($document); - - $properties = $structure->getProperties(true); - foreach ($properties as $property) { - $value = $this->getParser($format)->getPropertyData( - $property->getName(), - $data, - $property->getContentTypeName() - ); - - $this->importProperty($property, $node, $structure, $value, null, $locale, $format); - $document->getStructure()->getProperty($property->getName())->setValue($property->getValue()); - } - - // import extensions - $extensions = $this->extensionManager->getExtensions($document->getStructureType()); - - foreach ($extensions as $key => $extension) { - $extensionData = $this->importExtension($extension, $key, $node, $data, $locale, $format); - $document->setExtension($key, $extensionData); - } - - // set required data - $document->setTitle($this->getParser($format)->getPropertyData('title', $data)); - - return true; - } - - protected function setDocumentSettings( - ArticleDocument $document, - string $format, - array $data, - bool $overrideSettings - ): void { - if (!$overrideSettings) { - return; - } - - foreach ($data as $key => $property) { - $setter = 'set' . \ucfirst($key); - - if (\in_array($key, self::$excludedSettings) || !\method_exists($document, $setter)) { - continue; - } - - $value = $this->getParser($format)->getPropertyData( - $key, - $data - ); - - $document->$setter($this->getSetterValue($key, $value)); - } - } - - /** - * @param mixed $value - * - * @return mixed - */ - protected function getSetterValue(string $key, $value) - { - if (empty($value)) { - return null; - } - - switch ($key) { - case 'additionalWebspaces': - $value = \json_decode($value, true); - break; - case 'authored': - $value = new \DateTime($value); - break; - } - - return $value; - } - - protected function importExtension( - ExtensionInterface $extension, - string $extensionKey, - NodeInterface $node, - array $data, - string $locale, - string $format - ): array { - $extensionData = []; - - if ($extension instanceof ExportExtensionInterface) { - foreach ($extension->getImportPropertyNames() as $propertyName) { - $value = $this->getParser($format)->getPropertyData( - $propertyName, - $data, - null, - $extensionKey - ); - - $extensionData[$propertyName] = $value; - } - - $extension->import($node, $extensionData, null, $locale, $format); - } - - return $extension->load($node, null, $locale); - } -} diff --git a/Import/ArticleImportInterface.php b/Import/ArticleImportInterface.php deleted file mode 100644 index 322e15e12..000000000 --- a/Import/ArticleImportInterface.php +++ /dev/null @@ -1,25 +0,0 @@ -count = $count; - $this->fails = $fails; - $this->successes = $successes; - $this->failed = $failed; - $this->exceptionStore = $exceptionStore; - } - - public function getCount(): int - { - return $this->count; - } - - public function getFails(): int - { - return $this->fails; - } - - public function getSuccesses(): int - { - return $this->successes; - } - - public function getFailed(): array - { - return $this->failed; - } - - public function getExceptionStore(): array - { - return $this->exceptionStore; - } -} diff --git a/Infrastructure/Sulu/Content/ArticleContentQueryBuilder.php b/Infrastructure/Sulu/Content/ArticleContentQueryBuilder.php deleted file mode 100644 index 5ffac0220..000000000 --- a/Infrastructure/Sulu/Content/ArticleContentQueryBuilder.php +++ /dev/null @@ -1,177 +0,0 @@ -ids = $ids; - $this->propertiesConfig = \array_merge( - ['routePath' => new PropertyParameter('routePath', 'routePath')], - isset($options['properties']) ? $options['properties'] : [] - ); - $this->published = isset($options['published']) ? $options['published'] : false; - } - - /** - * @param string $webspaceKey - * @param string $locale - * - * @return string - */ - protected function buildWhere($webspaceKey, $locale) - { - $idsWhere = []; - - foreach ($this->ids as $id) { - $idsWhere[] = \sprintf("page.[jcr:uuid] = '%s'", $id); - } - - return '(' . \implode(' OR ', $idsWhere) . ')'; - } - - /** - * @param string $webspaceKey - * @param string $locale - * @param array> $additionalFields - * - * @return string - */ - protected function buildSelect($webspaceKey, $locale, &$additionalFields) - { - $select = []; - - if (\count($this->propertiesConfig) > 0) { - $this->buildPropertiesSelect($locale, $additionalFields); - } - - return \implode(', ', $select); - } - - /** - * @param string $locale - * @param array> $additionalFields - */ - private function buildPropertiesSelect($locale, &$additionalFields): void - { - foreach ($this->propertiesConfig as $parameter) { - $alias = $parameter->getName(); - /** @var string $propertyName */ - $propertyName = $parameter->getValue(); - - if (false !== \strpos($propertyName, '.')) { - $parts = \explode('.', $propertyName); - - $this->buildExtensionSelect($alias, $parts[0], $parts[1], $locale, $additionalFields); - } else { - $this->buildPropertySelect($alias, $propertyName, $locale, $additionalFields); - } - } - } - - /** - * @param string $alias - * @param string $propertyName - * @param string $locale - * @param array> $additionalFields - */ - private function buildPropertySelect($alias, $propertyName, $locale, &$additionalFields): void - { - foreach ($this->structureManager->getStructures(static::$structureType) as $structure) { - if ($structure->hasProperty($propertyName)) { - $property = $structure->getProperty($propertyName); - $additionalFields[$locale][] = [ - 'name' => $alias, - 'property' => $property, - 'templateKey' => $structure->getKey(), - ]; - } - } - } - - /** - * @param string $alias - * @param string $extension - * @param string $propertyName - * @param string $locale - * @param array> $additionalFields - */ - private function buildExtensionSelect($alias, $extension, $propertyName, $locale, &$additionalFields): void - { - $extension = $this->extensionManager->getExtension('all', $extension); - $additionalFields[$locale][] = [ - 'name' => $alias, - 'extension' => $extension, - 'property' => $propertyName, - ]; - } -} diff --git a/Infrastructure/Sulu/Headless/ContentTypeResolver/ArticleSelectionResolver.php b/Infrastructure/Sulu/Headless/ContentTypeResolver/ArticleSelectionResolver.php deleted file mode 100644 index e2836dd5b..000000000 --- a/Infrastructure/Sulu/Headless/ContentTypeResolver/ArticleSelectionResolver.php +++ /dev/null @@ -1,112 +0,0 @@ -structureResolver = $structureResolver; - $this->contentQueryBuilder = $contentQueryBuilder; - $this->contentMapper = $contentMapper; - $this->showDrafts = $showDrafts; - } - - public function resolve($data, PropertyInterface $property, string $locale, array $attributes = []): ContentView - { - /** @var string[]|null $ids */ - $ids = $data; - - if (empty($ids)) { - return new ContentView([], ['ids' => []]); - } - - /** @var PropertyParameter[] $params */ - $params = $property->getParams(); - /** @var PropertyParameter[] $propertiesParamValue */ - $propertiesParamValue = isset($params['properties']) ? $params['properties']->getValue() : []; - - $this->contentQueryBuilder->init([ - 'ids' => $ids, - 'properties' => $propertiesParamValue, - 'published' => !$this->showDrafts, - ]); - - /** @var array{string, mixed[]} $queryBuilderResult */ - $queryBuilderResult = $this->contentQueryBuilder->build($property->getStructure()->getWebspaceKey(), [$locale]); - list($articlesQuery) = $queryBuilderResult; - - $articleStructures = $this->contentMapper->loadBySql2( - $articlesQuery, - $locale, - $property->getStructure()->getWebspaceKey() - ); - - $propertyMap = [ - 'title' => 'title', - 'routePath' => 'routePath', - ]; - - foreach ($propertiesParamValue as $propertiesParamEntry) { - $paramName = $propertiesParamEntry->getName(); - $paramValue = $propertiesParamEntry->getValue(); - $propertyMap[$paramName] = \is_string($paramValue) ? $paramValue : $paramName; - } - - $articles = \array_fill_keys($ids, null); - - foreach ($articleStructures as $articleStructure) { - $articles[$articleStructure->getUuid()] = $this->structureResolver->resolveProperties($articleStructure, $propertyMap, $locale); - } - - return new ContentView(\array_values(\array_filter($articles)), ['ids' => $ids]); - } -} diff --git a/Infrastructure/Sulu/Headless/ContentTypeResolver/SingleArticleSelectionResolver.php b/Infrastructure/Sulu/Headless/ContentTypeResolver/SingleArticleSelectionResolver.php deleted file mode 100644 index 55b613712..000000000 --- a/Infrastructure/Sulu/Headless/ContentTypeResolver/SingleArticleSelectionResolver.php +++ /dev/null @@ -1,53 +0,0 @@ -articleSelectionResolver = $articleSelectionResolver; - } - - public function resolve($data, PropertyInterface $property, string $locale, array $attributes = []): ContentView - { - /** @var string|null $id */ - $id = $data; - - if (empty($id)) { - return new ContentView(null, ['id' => null]); - } - - $content = $this->articleSelectionResolver->resolve([$id], $property, $locale, $attributes); - - /** @var mixed[]|null $contentData */ - $contentData = $content->getContent(); - - return new ContentView($contentData[0] ?? null, ['id' => $id]); - } -} diff --git a/Infrastructure/Sulu/Headless/DataProviderResolver/AbstractArticleDataProviderResolver.php b/Infrastructure/Sulu/Headless/DataProviderResolver/AbstractArticleDataProviderResolver.php deleted file mode 100644 index d0509bbdc..000000000 --- a/Infrastructure/Sulu/Headless/DataProviderResolver/AbstractArticleDataProviderResolver.php +++ /dev/null @@ -1,168 +0,0 @@ -articleDataProvider = $articleDataProvider; - $this->structureResolver = $structureResolver; - $this->contentQueryBuilder = $contentQueryBuilder; - $this->contentMapper = $contentMapper; - $this->showDrafts = $showDrafts; - } - - public function getProviderConfiguration(): ProviderConfigurationInterface - { - return $this->articleDataProvider->getConfiguration(); - } - - /** - * @return PropertyParameter[] - */ - public function getProviderDefaultParams(): array - { - return $this->articleDataProvider->getDefaultPropertyParameter(); - } - - public function resolve( - array $filters, - array $propertyParameters, - array $options = [], - ?int $limit = null, - int $article = 1, - ?int $pageSize = null - ): DataProviderResult { - $providerResult = $this->articleDataProvider->resolveResourceItems( - $filters, - $propertyParameters, - $options, - $limit, - $article, - $pageSize, - ); - - /** @var string $webspaceKey */ - $webspaceKey = $options['webspaceKey']; - /** @var string $locale */ - $locale = $options['locale']; - - $articleIds = []; - foreach ($providerResult->getItems() as $resultItem) { - $articleIds[] = $resultItem->getId(); - } - - /** @var PropertyParameter[] $propertiesParamValue */ - $propertiesParamValue = isset($propertyParameters['properties']) ? $propertyParameters['properties']->getValue() : []; - - // the ArticleDataProvider resolves the data defined in the $propertiesParamValue using the default content types - // for example, this means that the result contains an array of media api entities instead of a raw array of ids - // to resolve the data with the resolvers of this bundle, we need to load the structures with the ContentMapper - $articleStructures = $this->loadArticleStructures( - $articleIds, - $propertiesParamValue, - $webspaceKey, - $locale, - ); - - $propertyMap = [ - 'title' => 'title', - 'routePath' => 'routePath', - ]; - - foreach ($propertiesParamValue as $propertiesParamEntry) { - $paramName = $propertiesParamEntry->getName(); - $paramValue = $propertiesParamEntry->getValue(); - $propertyMap[$paramName] = \is_string($paramValue) ? $paramValue : $paramName; - } - - $resolvedArticles = \array_fill_keys($articleIds, null); - - foreach ($articleStructures as $articleStructure) { - $resolvedArticles[$articleStructure->getUuid()] = $this->structureResolver->resolveProperties($articleStructure, $propertyMap, $locale); - } - - return new DataProviderResult(\array_values(\array_filter($resolvedArticles)), $providerResult->getHasNextPage()); - } - - /** - * @param string[] $articleIds - * @param PropertyParameter[] $propertiesParamValue - * - * @return StructureInterface[] - */ - private function loadArticleStructures(array $articleIds, array $propertiesParamValue, string $webspaceKey, string $locale): array - { - if (0 === \count($articleIds)) { - return []; - } - - $this->contentQueryBuilder->init([ - 'ids' => $articleIds, - 'properties' => $propertiesParamValue, - 'published' => !$this->showDrafts, - ]); - - /** @var array{string, mixed[]} $queryBuilderResult */ - $queryBuilderResult = $this->contentQueryBuilder->build($webspaceKey, [$locale]); - list($articlesQuery) = $queryBuilderResult; - - return $this->contentMapper->loadBySql2( - $articlesQuery, - $locale, - $webspaceKey, - ); - } -} diff --git a/Infrastructure/Sulu/Headless/DataProviderResolver/ArticleDataProviderResolver.php b/Infrastructure/Sulu/Headless/DataProviderResolver/ArticleDataProviderResolver.php deleted file mode 100644 index 541072bc3..000000000 --- a/Infrastructure/Sulu/Headless/DataProviderResolver/ArticleDataProviderResolver.php +++ /dev/null @@ -1,22 +0,0 @@ -structureResolver = $structureResolver; - $this->contentQueryBuilder = $contentQueryBuilder; - $this->contentMapper = $contentMapper; - $this->showDrafts = $showDrafts; - } - - public function resolve($data, PropertyInterface $property, string $locale, array $attributes = []): ContentView - { - /** @var string[]|null $ids */ - $ids = $data; - - if (empty($ids)) { - return new ContentView([], ['ids' => []]); - } - - /** @var PropertyParameter[] $params */ - $params = $property->getParams(); - /** @var PropertyParameter[] $propertiesParamValue */ - $propertiesParamValue = isset($params['properties']) ? $params['properties']->getValue() : []; - - $this->contentQueryBuilder->init([ - 'ids' => $ids, - 'properties' => $propertiesParamValue, - 'published' => !$this->showDrafts, - ]); - - /** @var array{string, mixed[]} $queryBuilderResult */ - $queryBuilderResult = $this->contentQueryBuilder->build($property->getStructure()->getWebspaceKey(), [$locale]); - list($articlesQuery) = $queryBuilderResult; - - $articleStructures = $this->contentMapper->loadBySql2( - $articlesQuery, - $locale, - $property->getStructure()->getWebspaceKey() - ); - - $propertyMap = [ - 'title' => 'title', - 'routePath' => 'routePath', - ]; - - foreach ($propertiesParamValue as $propertiesParamEntry) { - $paramName = $propertiesParamEntry->getName(); - $paramValue = $propertiesParamEntry->getValue(); - $propertyMap[$paramName] = \is_string($paramValue) ? $paramValue : $paramName; - } - - $articles = \array_fill_keys($ids, null); - - foreach ($articleStructures as $articleStructure) { - $articles[$articleStructure->getUuid()] = $this->structureResolver->resolveProperties($articleStructure, $propertyMap, $locale); - } - - return new ContentView(\array_values(\array_filter($articles)), ['ids' => $ids]); - } -} diff --git a/Infrastructure/SuluHeadlessBundle/ContentTypeResolver/SingleArticleSelectionResolver.php b/Infrastructure/SuluHeadlessBundle/ContentTypeResolver/SingleArticleSelectionResolver.php deleted file mode 100644 index 58bd34137..000000000 --- a/Infrastructure/SuluHeadlessBundle/ContentTypeResolver/SingleArticleSelectionResolver.php +++ /dev/null @@ -1,53 +0,0 @@ -articleSelectionResolver = $articleSelectionResolver; - } - - public function resolve($data, PropertyInterface $property, string $locale, array $attributes = []): ContentView - { - /** @var string|null $id */ - $id = $data; - - if (empty($id)) { - return new ContentView(null, ['id' => null]); - } - - $content = $this->articleSelectionResolver->resolve([$id], $property, $locale, $attributes); - - /** @var mixed[]|null $contentData */ - $contentData = $content->getContent(); - - return new ContentView($contentData[0] ?? null, ['id' => $id]); - } -} diff --git a/Infrastructure/SuluHeadlessBundle/DataProviderResolver/AbstractArticleDataProviderResolver.php b/Infrastructure/SuluHeadlessBundle/DataProviderResolver/AbstractArticleDataProviderResolver.php deleted file mode 100644 index e1548e0dd..000000000 --- a/Infrastructure/SuluHeadlessBundle/DataProviderResolver/AbstractArticleDataProviderResolver.php +++ /dev/null @@ -1,168 +0,0 @@ -articleDataProvider = $articleDataProvider; - $this->structureResolver = $structureResolver; - $this->contentQueryBuilder = $contentQueryBuilder; - $this->contentMapper = $contentMapper; - $this->showDrafts = $showDrafts; - } - - public function getProviderConfiguration(): ProviderConfigurationInterface - { - return $this->articleDataProvider->getConfiguration(); - } - - /** - * @return PropertyParameter[] - */ - public function getProviderDefaultParams(): array - { - return $this->articleDataProvider->getDefaultPropertyParameter(); - } - - public function resolve( - array $filters, - array $propertyParameters, - array $options = [], - ?int $limit = null, - int $article = 1, - ?int $pageSize = null - ): DataProviderResult { - $providerResult = $this->articleDataProvider->resolveResourceItems( - $filters, - $propertyParameters, - $options, - $limit, - $article, - $pageSize, - ); - - /** @var string $webspaceKey */ - $webspaceKey = $options['webspaceKey']; - /** @var string $locale */ - $locale = $options['locale']; - - $articleIds = []; - foreach ($providerResult->getItems() as $resultItem) { - $articleIds[] = $resultItem->getId(); - } - - /** @var PropertyParameter[] $propertiesParamValue */ - $propertiesParamValue = isset($propertyParameters['properties']) ? $propertyParameters['properties']->getValue() : []; - - // the ArticleDataProvider resolves the data defined in the $propertiesParamValue using the default content types - // for example, this means that the result contains an array of media api entities instead of a raw array of ids - // to resolve the data with the resolvers of this bundle, we need to load the structures with the ContentMapper - $articleStructures = $this->loadArticleStructures( - $articleIds, - $propertiesParamValue, - $webspaceKey, - $locale, - ); - - $propertyMap = [ - 'title' => 'title', - 'routePath' => 'routePath', - ]; - - foreach ($propertiesParamValue as $propertiesParamEntry) { - $paramName = $propertiesParamEntry->getName(); - $paramValue = $propertiesParamEntry->getValue(); - $propertyMap[$paramName] = \is_string($paramValue) ? $paramValue : $paramName; - } - - $resolvedArticles = \array_fill_keys($articleIds, null); - - foreach ($articleStructures as $articleStructure) { - $resolvedArticles[$articleStructure->getUuid()] = $this->structureResolver->resolveProperties($articleStructure, $propertyMap, $locale); - } - - return new DataProviderResult(\array_values(\array_filter($resolvedArticles)), $providerResult->getHasNextPage()); - } - - /** - * @param string[] $articleIds - * @param PropertyParameter[] $propertiesParamValue - * - * @return StructureInterface[] - */ - private function loadArticleStructures(array $articleIds, array $propertiesParamValue, string $webspaceKey, string $locale): array - { - if (0 === \count($articleIds)) { - return []; - } - - $this->contentQueryBuilder->init([ - 'ids' => $articleIds, - 'properties' => $propertiesParamValue, - 'published' => !$this->showDrafts, - ]); - - /** @var array{string, mixed[]} $queryBuilderResult */ - $queryBuilderResult = $this->contentQueryBuilder->build($webspaceKey, [$locale]); - list($articlesQuery) = $queryBuilderResult; - - return $this->contentMapper->loadBySql2( - $articlesQuery, - $locale, - $webspaceKey, - ); - } -} diff --git a/Infrastructure/SuluHeadlessBundle/DataProviderResolver/ArticleDataProviderResolver.php b/Infrastructure/SuluHeadlessBundle/DataProviderResolver/ArticleDataProviderResolver.php deleted file mode 100644 index f4af123c6..000000000 --- a/Infrastructure/SuluHeadlessBundle/DataProviderResolver/ArticleDataProviderResolver.php +++ /dev/null @@ -1,22 +0,0 @@ -sortField = $sortField ? $sortField : $name; - $this->searchField = $searchField; - - parent::__construct( - $name, - $translation, - $visibility, - $searchability, - $type, - $sortable - ); - } - - public function getSortField(): string - { - return $this->sortField; - } - - public function getSearchField(): string - { - return $this->searchField; - } -} diff --git a/ListBuilder/ElasticSearchFieldDescriptorBuilder.php b/ListBuilder/ElasticSearchFieldDescriptorBuilder.php deleted file mode 100644 index 03b6ddd21..000000000 --- a/ListBuilder/ElasticSearchFieldDescriptorBuilder.php +++ /dev/null @@ -1,113 +0,0 @@ -name = $name; - $this->translation = $translation; - } - - public function setSortField(string $sortField) - { - $this->sortField = $sortField; - $this->sortable = true; - - return $this; - } - - public function setVisibility(string $visibility) - { - $this->visibility = $visibility; - - return $this; - } - - public function setSearchability(string $searchability) - { - $this->searchability = $searchability; - - return $this; - } - - public function setType(string $type) - { - $this->type = $type; - - return $this; - } - - public function setSearchField(string $searchField): self - { - $this->searchField = $searchField; - - return $this; - } - - public function build(): ElasticSearchFieldDescriptor - { - return new ElasticSearchFieldDescriptor( - $this->name, - $this->sortField, - $this->translation, - $this->visibility, - $this->searchability, - $this->type, - $this->sortable, - $this->searchField, - ); - } -} diff --git a/Markup/ArticleLinkProvider.php b/Markup/ArticleLinkProvider.php deleted file mode 100644 index f468bf96e..000000000 --- a/Markup/ArticleLinkProvider.php +++ /dev/null @@ -1,150 +0,0 @@ -liveManager = $liveManager; - $this->defaultManager = $defaultManager; - $this->webspaceManager = $webspaceManager; - $this->requestStack = $requestStack; - $this->translator = $translator; - $this->types = $types; - $this->articleViewClass = $articleViewClass; - $this->environment = $environment; - } - - public function getConfiguration() - { - // TODO implement tabs again? - - return LinkConfigurationBuilder::create() - ->setTitle($this->translator->trans('sulu_article.articles', [], 'admin')) - ->setResourceKey('articles') - ->setListAdapter('table') - ->setDisplayProperties(['title']) - ->setOverlayTitle($this->translator->trans('sulu_article.single_selection_overlay_title', [], 'admin')) - ->setEmptyText($this->translator->trans('sulu_article.no_article_selected', [], 'admin')) - ->setIcon('su-newspaper') - ->getLinkConfiguration(); - } - - public function preload(array $hrefs, $locale, $published = true) - { - $request = $this->requestStack->getCurrentRequest(); - - $scheme = 'http'; - if ($request) { - $scheme = $request->getScheme(); - } - - $search = new Search(); - $search->addQuery(new IdsQuery($this->getViewDocumentIds($hrefs, $locale))); - $search->setSize(\count($hrefs)); - - $repository = $this->liveManager->getRepository($this->articleViewClass); - if (!$published) { - $repository = $this->defaultManager->getRepository($this->articleViewClass); - } - - $documents = $repository->findDocuments($search); - - $result = []; - /** @var ArticleViewDocumentInterface $document */ - foreach ($documents as $document) { - $result[] = $this->createLinkItem($document, $locale, $scheme); - } - - return $result; - } - - protected function createLinkItem(ArticleViewDocumentInterface $document, string $locale, string $scheme): LinkItem - { - $url = $this->webspaceManager->findUrlByResourceLocator( - $document->getRoutePath(), - $this->environment, - $locale, - $document->getTargetWebspace(), - null, - $scheme - ); - - return new LinkItem($document->getUuid(), $document->getTitle(), $url, $document->getPublishedState()); - } -} diff --git a/Metadata/ArticleViewDocumentIdTrait.php b/Metadata/ArticleViewDocumentIdTrait.php deleted file mode 100644 index 627ceaaa4..000000000 --- a/Metadata/ArticleViewDocumentIdTrait.php +++ /dev/null @@ -1,34 +0,0 @@ -getViewDocumentId($uuid, $locale); - } - - return $ids; - } -} diff --git a/Metadata/ListMetadataVisitor.php b/Metadata/ListMetadataVisitor.php deleted file mode 100644 index e36d89278..000000000 --- a/Metadata/ListMetadataVisitor.php +++ /dev/null @@ -1,117 +0,0 @@ - - */ - private $articleTypeConfigurations; - - /** - * @param array $articleTypeConfigurations - */ - public function __construct(StructureManagerInterface $structureManager, array $articleTypeConfigurations) - { - $this->structureManager = $structureManager; - $this->articleTypeConfigurations = $articleTypeConfigurations; - } - - public function visitListMetadata(ListMetadata $listMetadata, string $key, string $locale, array $metadataOptions = []): void - { - if ('articles' !== $key) { - return; - } - - $typeField = $listMetadata->getField('type'); - - $types = $this->getTypes(); - if (1 === \count($types)) { - $typeField->setFilterType(null); - $typeField->setFilterTypeParameters(null); - - return; - } - - $options = []; - foreach ($types as $type) { - $options[$type['type']] = $type['title']; - } - - $typeField->setFilterTypeParameters(['options' => $options]); - } - - /** - * @return array - */ - private function getTypes(): array - { - $types = []; - - // prefill array with keys from configuration to keep order of configuration for tabs - foreach ($this->articleTypeConfigurations as $typeKey => $articleTypeConfiguration) { - $types[$typeKey] = [ - 'type' => $typeKey, - 'title' => $this->getTitle($typeKey), - ]; - } - - /** @var StructureBridge $structure */ - foreach ($this->structureManager->getStructures('article') as $structure) { - /** @var string|null $type */ - $type = $this->getType($structure->getStructure(), null); - $typeKey = $type ?: 'default'; - if (empty($types[$typeKey])) { - $types[$typeKey] = [ - 'type' => $typeKey, - 'title' => $this->getTitle($typeKey), - ]; - } - } - - return $types; - } - - private function getTitle(string $type): string - { - if (!\array_key_exists($type, $this->articleTypeConfigurations)) { - return \ucfirst($type); - } - - return $this->articleTypeConfigurations[$type]['translation_key']; - } -} diff --git a/Metadata/StructureTagTrait.php b/Metadata/StructureTagTrait.php deleted file mode 100644 index 98d3ef674..000000000 --- a/Metadata/StructureTagTrait.php +++ /dev/null @@ -1,62 +0,0 @@ -getTagAttribute($metadata, ArticleAdmin::STRUCTURE_TAG_TYPE, 'type', $default); - } - - /** - * Returns multipage-configuration for given structure-metadata. - * - * @return mixed - */ - protected function getMultipage(StructureMetadata $metadata) - { - return $this->getTagAttribute($metadata, ArticleAdmin::STRUCTURE_TAG_MULTIPAGE, 'enabled', false); - } - - /** - * Returns attribute for given tag in metadata. - * - * @param mixed $default - * - * @return mixed - */ - private function getTagAttribute(StructureMetadata $metadata, string $tag, string $attribute, $default) - { - if (!$metadata->hasTag($tag)) { - return $default; - } - - $tag = $metadata->getTag($tag); - if (!\array_key_exists($attribute, $tag['attributes'])) { - return $default; - } - - return $tag['attributes'][$attribute]; - } -} diff --git a/Preview/ArticleObjectProvider.php b/Preview/ArticleObjectProvider.php deleted file mode 100644 index 06a43875b..000000000 --- a/Preview/ArticleObjectProvider.php +++ /dev/null @@ -1,202 +0,0 @@ -documentManager = $documentManager; - $this->serializer = $serializer; - $this->articleDocumentClass = $articleDocumentClass; - $this->structureMetadataFactory = $structureMetadataFactory; - } - - public function getObject($id, $locale) - { - return $this->documentManager->find( - $id, - $locale, - [ - 'load_ghost_content' => false, - 'load_shadow_content' => true, - ] - ); - } - - /** - * @param ArticleDocument $object - */ - public function getId($object) - { - return $object->getUuid(); - } - - /** - * @param ArticleDocument $object - */ - public function setValues($object, $locale, array $data) - { - $propertyAccess = PropertyAccess::createPropertyAccessorBuilder() - ->enableMagicCall() - ->getPropertyAccessor(); - - $structure = $object->getStructure(); - foreach ($data as $property => $value) { - try { - if ('ext' === $property) { - $object->setExtensionsData(new ExtensionContainer($value)); - continue; - } - - $propertyAccess->setValue($structure, $property, $value); - } catch (\InvalidArgumentException $e) { - // @ignoreException - //ignore not existing properties - } - } - } - - /** - * @param ArticleDocument $object - */ - public function setContext($object, $locale, array $context) - { - if (\array_key_exists('template', $context)) { - $object->setStructureType($context['template']); - } - - return $object; - } - - /** - * @param ArticleDocument $object - */ - public function serialize($object) - { - $pageNumber = $object->getPageNumber(); - if ($object instanceof ArticlePageDocument) { - // resolve proxy to ensure that this will also be serialized - $object = $object->getParent(); - - $object->getTitle(); - } - - $result = $this->serializer->serialize( - $object, - 'json', - SerializationContext::create() - ->setSerializeNull(true) - ->setGroups(['preview']) - ); - - return \json_encode(['pageNumber' => $pageNumber, 'object' => $result]); - } - - /** - * @param ArticleDocument $serializedObject - */ - public function deserialize($serializedObject, $objectClass) - { - $result = \json_decode($serializedObject, true); - - $article = $this->serializer->deserialize( - $result['object'], - $this->articleDocumentClass, - 'json', - DeserializationContext::create() - ->setGroups(['preview']) - ); - - foreach ($article->getChildren() as $child) { - $child->setParent($article); - } - - if (1 === $result['pageNumber']) { - return $article; - } - - $children = \array_values($article->getChildren()); - - $object = $children[$result['pageNumber'] - 2]; - - return $object; - } - - public function getSecurityContext($id, $locale): ?string - { - /** @var ArticleDocument $object */ - $object = $this->getObject($id, $locale); - $articleType = $this->getArticleType($object); - if (!$articleType) { - return ArticleAdmin::SECURITY_CONTEXT; - } - - return ArticleAdmin::getArticleSecurityContext($articleType); - } - - private function getArticleType(ArticleDocument $articleDocument): ?string - { - $structureMetadata = $this->structureMetadataFactory->getStructureMetadata( - 'article', - $articleDocument->getStructureType() - ); - - if (!$structureMetadata) { - return null; - } - - return $this->getType($structureMetadata); - } -} diff --git a/Reference/Provider/ArticleReferenceProvider.php b/Reference/Provider/ArticleReferenceProvider.php deleted file mode 100644 index ec6e2253d..000000000 --- a/Reference/Provider/ArticleReferenceProvider.php +++ /dev/null @@ -1,62 +0,0 @@ - $document->getWebspaceName(), - ]); - } -} diff --git a/Reference/Refresh/ArticleReferenceRefresher.php b/Reference/Refresh/ArticleReferenceRefresher.php deleted file mode 100644 index b2266c1e0..000000000 --- a/Reference/Refresh/ArticleReferenceRefresher.php +++ /dev/null @@ -1,85 +0,0 @@ -session->getWorkspace()->getQueryManager(); - $query = $queryManager->createQuery($sql2, 'JCR-SQL2'); - $queryResult = $query->execute(); - - /** @var RowIterator $rows */ - $rows = $queryResult->getRows(); - - foreach ($this->webspaceManager->getAllLocalizations() as $localization) { - $locale = $localization->getLocale(); - /** @var Row $row */ - foreach ($rows as $row) { - /** @var string $uuid */ - $uuid = $row->getValue('jcr:uuid'); - /** @var (UuidBehavior&TitleBehavior&StructureBehavior)|null $document */ - $document = $this->documentManager->find( - $uuid, - $locale, - [ - 'load_ghost_content' => false, - ] - ); - - if (!$document) { - continue; - } - - $this->documentReferenceProvider->updateReferences($document, $locale, $this->suluContext); - - yield $document; - } - - $this->documentManager->clear(); // the cache is locale independent, so we need to clear between locale changes - } - } -} diff --git a/Resolver/ArticleContentResolver.php b/Resolver/ArticleContentResolver.php deleted file mode 100644 index b3155ce62..000000000 --- a/Resolver/ArticleContentResolver.php +++ /dev/null @@ -1,138 +0,0 @@ -serializer = $serializer; - $this->structureManager = $structureManager; - $this->extensionManager = $extensionManager; - $this->contentProxyFactory = $contentProxyFactory; - } - - public function resolve(ArticleInterface $article, int $pageNumber = 1) - { - $data = $this->serializer->serialize( - $article, - SerializationContext::create() - ->setSerializeNull(true) - ->setGroups(['website', 'content']) - ->setAttribute('pageNumber', $pageNumber) - ->setAttribute('urls', true) - ); - - if ($article instanceof ArticlePageDocument) { - $article = $article->getParent(); - } - - $data['page'] = $pageNumber; - $data['pages'] = $article->getPages(); - - $article = $this->getArticleForPage($article, $pageNumber); - - $data['id'] = $article->getArticleUuid(); - $data['uuid'] = $article->getArticleUuid(); - $data['pageUuid'] = $article->getPageUuid(); - - $data = \array_merge($data, $this->resolveContent($article)); - - return $data; - } - - /** - * Returns article page by page-number. - */ - private function getArticleForPage(ArticleDocument $article, int $pageNumber): ArticleDocument - { - $children = $article->getChildren(); - if (null === $children || 1 === $pageNumber) { - return $article; - } - - foreach ($children as $child) { - if ($child instanceof ArticlePageDocument && $child->getPageNumber() === $pageNumber) { - return $child; - } - } - - return $article; - } - - /** - * Returns content and view of article. - */ - private function resolveContent(ArticleDocument $article): array - { - /** @var StructureBridge $structure */ - $structure = $this->structureManager->getStructure($article->getStructureType(), 'article'); - $structure->setDocument($article); - - $data = $article->getStructure()->toArray(); - - $extension = []; - - $extensionData = $article->getExtensionsData(); - if ($extensionData instanceof ExtensionContainer) { - $extensionData = $extensionData->toArray(); - } - - foreach ($extensionData as $name => $value) { - $extension[$name] = $this->extensionManager->getExtension('article', $name)->getContentData($value); - } - - $content = $this->contentProxyFactory->createContentProxy($structure, $data); - $view = $this->contentProxyFactory->createViewProxy($structure, $data); - - return [ - 'content' => $content, - 'view' => $view, - 'extension' => $extension, - ]; - } -} diff --git a/Resolver/ArticleContentResolverInterface.php b/Resolver/ArticleContentResolverInterface.php deleted file mode 100644 index 8b44a3592..000000000 --- a/Resolver/ArticleContentResolverInterface.php +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - %sulu_article.article_document.class% - - - - - - diff --git a/Resources/config/forms/article_settings.xml b/Resources/config/forms/article_settings.xml deleted file mode 100644 index 202855a2f..000000000 --- a/Resources/config/forms/article_settings.xml +++ /dev/null @@ -1,143 +0,0 @@ - -
- article_settings - - - - - - - - - - - - - - - - - - - - - - - - - sulu_article.webspace_settings - - - - - - sulu_article.customize_webspace_settings - - - - - - - - - sulu_article.main_webspace - - - - - - - - - - sulu_article.additional_webspace - - - - - - - - -
- - sulu_article.shadow_article - - - - - sulu_article.shadow_article - sulu_page.enable_shadow_page_info_text - - - - - - sulu_article.enable_shadow_article - - - - - - - sulu_page.shadow_locale - - - -
- -
- - sulu_page.editing_information - - - - - sulu_article.last_modified_enabled - - - - - - - - - - sulu_article.last_modified_date - - - - - sulu_page.authored_date - - - - - sulu_page.author - - - - - sulu_page.changelog - - - -
-
-
diff --git a/Resources/config/forms_sulu_25_or_lower/article_settings.xml b/Resources/config/forms_sulu_25_or_lower/article_settings.xml deleted file mode 100644 index f425626c9..000000000 --- a/Resources/config/forms_sulu_25_or_lower/article_settings.xml +++ /dev/null @@ -1,128 +0,0 @@ - -
- article_settings - - - - - - - - - - - - - - - - - - - - - - - - - sulu_article.webspace_settings - - - - - - sulu_article.customize_webspace_settings - - - - - - - - - sulu_article.main_webspace - - - - - - - - - - sulu_article.additional_webspace - - - - - - - - -
- - sulu_article.shadow_article - - - - - sulu_article.shadow_article - sulu_page.enable_shadow_page_info_text - - - - - - sulu_article.enable_shadow_article - - - - - - - sulu_page.shadow_locale - - - -
- -
- - sulu_page.editing_information - - - - - sulu_page.authored_date - - - - - sulu_page.author - - - - - sulu_page.changelog - - - -
-
-
diff --git a/Resources/config/lists/article_versions.xml b/Resources/config/lists/article_versions.xml deleted file mode 100644 index 9e7f3453b..000000000 --- a/Resources/config/lists/article_versions.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - article_versions - - - - - - diff --git a/Resources/config/lists/articles.xml b/Resources/config/lists/articles.xml deleted file mode 100644 index 8ff02ef04..000000000 --- a/Resources/config/lists/articles.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - articles - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Resources/config/routing_api.yml b/Resources/config/routing_api.yml deleted file mode 100644 index 32496f1fe..000000000 --- a/Resources/config/routing_api.yml +++ /dev/null @@ -1,15 +0,0 @@ -sulu_article.article: - type: rest - resource: Sulu\Bundle\ArticleBundle\Controller\ArticleController - name_prefix: sulu_article. - -sulu_article.article_page: - type: rest - resource: Sulu\Bundle\ArticleBundle\Controller\ArticlePageController - name_prefix: sulu_article. - -sulu_article.article.versioning: - type: rest - resource: Sulu\Bundle\ArticleBundle\Controller\VersionController - name_prefix: sulu_article. - parent: sulu_article.article diff --git a/Resources/config/serializer/Document.ArticleDocument.xml b/Resources/config/serializer/Document.ArticleDocument.xml deleted file mode 100644 index 5ceabb96a..000000000 --- a/Resources/config/serializer/Document.ArticleDocument.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - ]]> - - - - - - - - - - - - - - - diff --git a/Resources/config/serializer/Document.ArticlePageDocument.xml b/Resources/config/serializer/Document.ArticlePageDocument.xml deleted file mode 100644 index 50d8d0073..000000000 --- a/Resources/config/serializer/Document.ArticlePageDocument.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Resources/config/serializer/Document.ArticleViewDocument.xml b/Resources/config/serializer/Document.ArticleViewDocument.xml deleted file mode 100644 index a9fb4f9a3..000000000 --- a/Resources/config/serializer/Document.ArticleViewDocument.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/Resources/config/serializer/Document.LocalizationStateViewObject.xml b/Resources/config/serializer/Document.LocalizationStateViewObject.xml deleted file mode 100644 index 0a358b119..000000000 --- a/Resources/config/serializer/Document.LocalizationStateViewObject.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/Resources/config/services.xml b/Resources/config/services.xml deleted file mode 100644 index 91a082c34..000000000 --- a/Resources/config/services.xml +++ /dev/null @@ -1,557 +0,0 @@ - - - - - - - @SuluArticle/Export/Article/1.2.xliff.twig - - - - - - - - - - - %sulu.context% - - - - - - - - - %kernel.bundles% - %sulu_article.types% - %sulu_document_manager.versioning.enabled% - - - - - - - - - - - - - - - - - - - - - - %sulu_article.display_tab_all% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %sulu_article.documents% - - - - - - - - - - - - - - - %sulu_article.types% - - - - - - - - - - - - - - - - %sulu_article.types% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %kernel.environment% - - - - - - - - - - - - - %sulu_article.view_document.article.class% - %sulu_article.smart_content.default_limit% - - - container.hasParameter('sulu_audience_targeting.enabled') - - - - - - - - - - %sulu_article.view_document.article.class% - %sulu_article.smart_content.default_limit% - - - - - - - %sulu_article.view_document.article.class% - - - - - - - %sulu.content.language.namespace% - - - - - - - - - - - - - - - - %sulu_article.article_document.class% - - - - - - - - - - - - - %sulu_article.types% - %sulu_article.view_document.article.class% - %kernel.environment% - - - - - - - - - - - - - - - %sulu_article.view_document.article.class% - - - - - - - - %sulu_article.view_document.article.class% - - - - - - - - - - - - - - %sulu_article.view_document.article.class% - %sulu_article.search_fields% - - - - - - - - - - - - - - - - - - - - %sulu_article.default_main_webspace% - %sulu_article.default_additional_webspaces% - - - - - - - - - - - - - - - - - - %sulu_article.view_document.article.class% - - - - - - - - - - - - - - - - - %sulu_article.export.article.formats% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %sulu_article.types% - - - - - diff --git a/Resources/config/services_headless.xml b/Resources/config/services_headless.xml deleted file mode 100644 index 8b1175cb4..000000000 --- a/Resources/config/services_headless.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - %sulu_document_manager.show_drafts% - - - - - - - - - - - - - - - - %sulu_document_manager.show_drafts% - - - - - - - - - - %sulu_document_manager.show_drafts% - - - - - diff --git a/Resources/config/services_reference.xml b/Resources/config/services_reference.xml deleted file mode 100644 index cd8413e9d..000000000 --- a/Resources/config/services_reference.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - %sulu.context% - - - - - diff --git a/Resources/config/services_trash.xml b/Resources/config/services_trash.xml deleted file mode 100644 index 09b85ad69..000000000 --- a/Resources/config/services_trash.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/Resources/doc/README.md b/Resources/doc/README.md deleted file mode 100644 index 486268cdb..000000000 --- a/Resources/doc/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Documentation of SuluArticleBundle - -This documentation covers basic-topics to install and use this bundle. - -## List of content - -* [Installation](installation.md) -* [Routing](routing.md) -* [Overview-Page](overview-page.md) -* [Content-Types](content-types.md) -* [ArticleViewDocument](article-view-document.md) -* [Twig-Extensions](twig-extensions.md) -* [Commands](commands.md) -* [Author](author.md) -* [Article Types](article-types.md) -* [Multi Webspaces](multi-webspaces.md) -* [XLIFF Export / Import](xliff.md) diff --git a/Resources/doc/article-types.md b/Resources/doc/article-types.md deleted file mode 100644 index 99710e0e7..000000000 --- a/Resources/doc/article-types.md +++ /dev/null @@ -1,43 +0,0 @@ -# Article Types - -The SuluArticleBundle provides an additional way to divide different types of templates and group articles in the -Sulu-Admin. The article type of a template is set with the `sulu_article.type` tag. - -This has following impacts: - -* The article list in the Sulu-Admin will be extended by a tab-navigation to filter for article-types. -* Permissions in the settings area of the Sulu-Admin are managed separately for each article type. -* When changing the template of an article, you can only choose templates with the same article-type. - -> To allow users to see a newly added article type, you need to add the permissions for the article to the respective user roles - -The article-type can also be used for querying the elastic-search index, it is stored in the field `type`. - -## Sulu-Admin translations - -To translate the name of the type in the Sulu-Admin UI you can use the following configuration snippet: - -```yml -sulu_article: - types: - my_article_type: - translation_key: "app.article_types.my_article_type" -``` - -This key can the be used to translate the key by adding a Translation File `translations/admin.en.json`. - -## Usage in Content-Types - -### Smart-Content - -The type can also be used to predefine a filter for the smart-content provider for articles. You can simply add the following param to the template definition: - -```xml - - - - - -``` - -This will filter the smart-content for the given two types of articles. diff --git a/Resources/doc/article-view-document.md b/Resources/doc/article-view-document.md deleted file mode 100644 index 89528fded..000000000 --- a/Resources/doc/article-view-document.md +++ /dev/null @@ -1,181 +0,0 @@ -# ArticleViewDocument - -This object is used to index article data in Elasticsearch. This index is used to query data where more than one article -is requested (content-types, smart-content, ...). - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| uuid | string | | -| locale | string | | -| title | string | | -| routePath | string | | -| type | string | | -| structureType | string | Key of the XML Template file | -| changerFullName | string | Fullname of the changer | -| creatorFullName | string | Fullname of the creator | -| authorFullName | string | Fullname of the author | -| changed | DateTime | Timestamp of last modification | -| created | DateTime | Timestamp of creation | -| authored | DateTime | Managed timestamp of publication | -| published | DateTime | Timestamp of publication | -| excerpt | ExcerptViewObject | Full resolved (incl. media formats) of excerpt data | -| seo | SeoViewObject | Data of excerpt data | -| pages | ArticlePageViewObject[] | Content of pages (incl. content and view) | -| content | array | Resolved content from raw-data | -| view | array | Resolved view from raw-data | -| targetWebspace | string | Recommended webspace key | -| mainWebspace | string | Configured main webspace | -| additionalWebspaces | string[] | Configured additional webspaces | -| contentFields | string[] | Contains content properties tagged with `sulu.search.field` | - -The `content` and `view` property is represented by a proxy to avoid resolving data where it is not needed. - -### ContentFields - -The content of the property `contentFields` can be customized. All properties which are tagged with -`sulu.search.field` in the xml configuration, are automatically added to this field. The main purpose of this field -is to give the developer enough data and flexibility to implement search functionality via e.g. a `SearchController`. - -Example: -```xml - - - Text - Text - - - - -``` - -## How to extend? - -To extend the indexed data you can extend the `ArticleViewDocument`. This can be achieved by performing the following -steps. The same steps can also be used to extend the `ArticlePageViewObject`. - -### 0. Create a Bundle Class - -Unfortunately, the ElasticsearchBundle allows to overwrite document classes only if an `AppBundle` is registered in the -application. If you do not have registered such a bundle yet, you need to add it to your `src` directory and enable it -in the `config/bundles.php` file. - -```php - ['all' => true], -] -``` - -#### 1. Create custom class - -```php -getDocument(); - $viewDocument = $event->getViewDocument(); - $data = $document->getStructure()->toArray(); - - if (!array_key_exists('myCustomProperty', $data)) { - return; - } - - $viewDocument->myCustomProperty = $data['myCustomProperty']; - } -} -``` - -```xml - - - -``` diff --git a/Resources/doc/author.md b/Resources/doc/author.md deleted file mode 100644 index 44b1bf639..000000000 --- a/Resources/doc/author.md +++ /dev/null @@ -1,15 +0,0 @@ -# Author - -The author is a value which can be set by the content-manager. By default set the creator as the author on creation time -and the content-manager can select another contact in the settings-tab. Therefor the author is a prefilled mandatory -value. - -This behavior can be influenced by the configuration and make the author an optional nullable value. - -```yaml -sulu_article: - default_author: false -``` - -When this configuration isset the author will no be prefilled and can be set optional in the settings-tab. If is was not -set the `author` variable in twig will stay `null`. diff --git a/Resources/doc/commands.md b/Resources/doc/commands.md deleted file mode 100644 index 8c5a4b5ac..000000000 --- a/Resources/doc/commands.md +++ /dev/null @@ -1,37 +0,0 @@ -# Commands - -## Reindex command - -The reindex command can be used to rebuild the elastic-search index of the articles. - -```bash -bin/adminconsole sulu:article:reindex -bin/websiteconsole sulu:article:reindex -``` - -The default behaviour of the command is to load all the articles and update the content of them. This includes that -deleted articles (which was not removed correctly from index) will stay inside the index. - -To avoid this behaviour you can use the `--clear` option to remove all the articles from the index before reindex the -existing ones. - -```bash -bin/adminconsole sulu:article:reindex --clear -bin/websiteconsole sulu:article:reindex --clear -``` - -Sometimes you want to update also the mapping of the index. To achieve this you can use the `--drop` option. This will -drop and recreate the index with the current mapping. - -```bash -bin/adminconsole sulu:article:reindex --drop -bin/websiteconsole sulu:article:reindex --drop -``` - -This options will answer you the confirm this operation. To avoid this interaction you can use the `--no-interaction` -option. - -```bash -bin/adminconsole sulu:article:reindex --drop --no-interaction -bin/websiteconsole sulu:article:reindex --drop --no-interaction -``` diff --git a/Resources/doc/content-types.md b/Resources/doc/content-types.md deleted file mode 100644 index 9c73a466a..000000000 --- a/Resources/doc/content-types.md +++ /dev/null @@ -1,116 +0,0 @@ -# Content-Types - -The SuluArticleBundle provides 3 ways to include articles into another page (or article). - -1. Direct assignment: `article_selection` or `single_article_selection` -2. Smart-Content: `articles` or `articles_page_tree` -2. Teaser-Selection: `article` - -## Article-Selection - -Allows to select articles and assign them to another page or article. - -### Parameters - -| Name | Type | Description | -|-------|---------|-----------------------------------------------------| -| types | string | Comma separated list of types which can be selected | - -### Returns - -The content-type returns a list of [ArticleViewDocumentInterface](article-view-document.md) instances. - -### Example - -```xml - - - Articles - Artikel - - -``` - -## Single-Article-Selection - -Allows to select a single article and assign it to another page or article. - -### Parameters - -| Name | Type | Description | -|-------|---------|-----------------------------------------------------| -| types | string | Comma separated list of types which can be selected | - -### Returns - -The content-type returns a single [ArticleViewDocumentInterface](article-view-document.md) instance. - -### Example - -```xml - - - Article - Artikel - - -``` - -## Smart-Content - -This bundle provides also a way to include articles in the -[Smart-Content](http://docs.sulu.io/en/latest/reference/content-types/smart_content.html). -This allows to create dynamic lists of articles for example on overview-pages. - -There exists 2 different providers which does almost the same. The only difference is that -the `articles_page_tree` allows to select a page as data-source which will be used to filter -the articles. - -**Alias:** `articles` or `articles_page_tree` - -### Parameters - -| Name | Type | Description | -|------------------|---------|-------------------------------------------------------------------------------------| -| types | string | Comma separated list of types which can be selected | -| structureTypes | string | Comma separated list of structure types (template keys) which can be selected | -| ignoreWebspaces | bool | If set to `true` all articles will be loaded, otherwise the webspace needs to match | - -### Returns - -The content-type returns a list of `ArticleResourceItem` (get the underlying -[ArticleViewDocumentInterface](article-view-document.md) with `ArticleResourceItem::getContent()`) instances. - -### Example - -```xml - - - Articles - Artikel - - - - - - -``` - -## Teaser-Selection - -Also for the [teaser-selection](http://docs.sulu.io/en/latest/reference/content-types/teaser_selection.html) -an `article` provider exists. - -It allows to include there also articles. Same as for the pages, the data for the `Teaser` -will be extracted from the excerpt or defined properties (`title`, `sulu.teaser.description` or -`sulu.teaser.media`) - -Additionally this Teaser contains following attributes: - -| Name | Type | Description | -|---------------|---------|-----------------------------------| -| structureType | string | Key of selected template | -| type | string | Article-Type of selected template | - -To use this attributes use `{{ teaser.attributes.structureType }}` but wrap it with a if-statement -to ensure that this is only used for article teasers. diff --git a/Resources/doc/default.html.twig b/Resources/doc/default.html.twig deleted file mode 100644 index 9406b661a..000000000 --- a/Resources/doc/default.html.twig +++ /dev/null @@ -1,9 +0,0 @@ -{% extends "base.html.twig" %} - -{% block content %} -

{{ content.title }}

- -
- {{ content.article|default()|raw }} -
-{% endblock %} diff --git a/Resources/doc/default.xml b/Resources/doc/default.xml deleted file mode 100644 index 4773faacb..000000000 --- a/Resources/doc/default.xml +++ /dev/null @@ -1,50 +0,0 @@ - - diff --git a/Resources/doc/experimental-storage.md b/Resources/doc/experimental-storage.md deleted file mode 100644 index cbd19e35a..000000000 --- a/Resources/doc/experimental-storage.md +++ /dev/null @@ -1,120 +0,0 @@ -# Experimental Content Bundle Storage - -For the **experimental** storage the articles are stored using the [SuluContentBundle](https://github.com/sulu/sulucontentbundle). - -## Table of content - - - [Installation](#installation) - - [Routes](#routes) - - [Configuration](#configuration) - - [Override Entities](#override-entities) - - [Override Article Entity](#override-article-entity) - - [Override Article Content Entity](#override-article-entity) - -## Installation - -To use the experimental storage you need to have the [SuluContentBundle](https://github.com/sulu/sulucontentbundle) installed. - -```bash -composer require sulu/content-bundle -``` - -Then you can configure it: - -```yaml -sulu_article: - article: - storage: experimental -``` - -## Routes - -```yaml -# config/routes/sulu_article_admin.yaml - -## coming soon ... -``` - -## Configuration - -The following is showing the full configuration of the **experimental** article module: - -```yaml -sulu_product: - storage: experimental - - # optional - objects: - article: - model: 'Sulu\Bundle\ArticleBundle\Domain\Model\Article' - article_content: - model: 'Sulu\Bundle\ArticleBundle\Domain\Model\ArticleDimensionContent' -``` - -## Override Entities - -### Override Article Entity - -```php - User Roles` - -## Possible bundle configurations: - -```yml -# config/packages/sulu_article.yaml - -sulu_article: - index_name: su_articles - hosts: ['127.0.0.1:9200'] - default_main_webspace: null - default_additional_webspaces: [] - smart_content: - default_limit: 100 - documents: - article: - view: Sulu\Bundle\ArticleBundle\Document\ArticleViewDocument - article_page: - view: Sulu\Bundle\ArticleBundle\Document\ArticlePageViewObject - types: - # Prototype - name: - translation_key: ~ - - # Display tab 'all' in list view - display_tab_all: true - - # Set default author if none isset - default_author: true - search_fields: - - # Defaults: - - title - - excerpt.title - - excerpt.description - - excerpt.seo.title - - excerpt.seo.description - - excerpt.seo.keywords - - teaser_description -``` - -## Troubleshooting - -### Add bundles to AbstractKernel - -The bundle need to be registered after the `SuluCoreBundle` and `SuluDocumentManagerBundle`. This should be done -automatically by Symfony Flex, if that fails for some reason you have to do it manually: - -```php -/* config/bundles.php */ - -Sulu\Bundle\ArticleBundle\SuluArticleBundle::class => ['all' => true], -ONGR\ElasticsearchBundle\ONGRElasticsearchBundle::class => ['all' => true], -``` diff --git a/Resources/doc/multi-webspaces.md b/Resources/doc/multi-webspaces.md deleted file mode 100644 index 4f4278797..000000000 --- a/Resources/doc/multi-webspaces.md +++ /dev/null @@ -1,24 +0,0 @@ -# Multi Webspaces - -When you have more than one webspace in your Sulu installation you should provide a default main webspace and optional additional webspaces for which the article is valid. - -## Functionality - -Normally an article will be delivered only for the main webspace. Further an article can be delivered for -the additional webspaces which are configured. To prevent duplicate content issues a canonical tag with the -url for the main webspace is inclued in the HTML head. - -More information about this topic: -* Duplicate content: https://moz.com/learn/seo/duplicate-content -* Canonicalization: https://moz.com/learn/seo/canonicalization - -## Content Manager - -For each article the default webspace configuration can be overwritten by the content manager. - -## URL Generation - -The twig method [`sulu_content_path`](http://docs.sulu.io/en/latest/reference/twig-extensions/functions/sulu_content_path.html) can generate url with another webspace. -Just give this method the `targetWebspace` of the article as second argument. - -For example: `sulu_content_path(article.routePath, article.targetWebspace)`. diff --git a/Resources/doc/overview-page.md b/Resources/doc/overview-page.md deleted file mode 100644 index d49006cb5..000000000 --- a/Resources/doc/overview-page.md +++ /dev/null @@ -1,195 +0,0 @@ -# Overview Page - -This bundle provides multiple ways to create a overview page. - -## Content Types - -The first possibility to create a overview page is to use the build in functionality of Sulu. - -* Manually: Article-Selection (see [Content-Types](content-types.md#article-selection)) -* Automatic: Smart-Content with article provider (see [Content-Types](content-types.md#smart-content)) - -Both can be influenced by the content-manager (selection of articles or configuring the filter). - -## Custom Controller - -Another way is to create a custom controller. - -```xml - - -``` - -In this controller the articles can be loaded by using a custom elastic-search query. -See [here](http://docs.ongr.io/ElasticsearchDSL/HowTo/HowToSearch) for more information. - -```php -esManagerLive = $esManagerLive; - } - - public function indexAction(Request $request, StructureInterface $structure, $preview = false, $partial = false) - { - $page = $request->query->getInt('page', 1); - if ($page < 1) { - throw new NotFoundHttpException(); - } - - $articles = $this->loadArticles($page, self::PAGE_SIZE, $request->getLocale()); - - $pages = (int) ceil($articles->count() / self::PAGE_SIZE) ?: 1; - - return $this->renderStructure( - $structure, - [ - 'page' => $page, - 'pages' => $pages, - 'articles' => $articles - ], - $preview, - $partial - ); - } - - private function loadArticles($page, $pageSize, $locale) - { - $repository = $this->getRepository(); - $search = $repository->createSearch() - ->addSort(new FieldSort('authored', FieldSort::DESC)) - ->setFrom(($page - 1) * $pageSize) - ->setSize($pageSize) - ->addQuery(new TermQuery('locale', $locale)); - - return $repository->findDocuments($search); - } - - /** - * @return Repository - */ - private function getRepository() - { - return $this->esManagerLive->getRepository(ArticleViewDocument::class); - } -} -``` - -That the `$esManagerLive` is correctly set you need to add the following to your `config/services.yaml` - -```yaml -services: - # default configuration for services in *this* file - _defaults: - autowire: true # Automatically injects dependencies in your services. - autoconfigure: true # Automatically registers your services as commands, event subscribers, etc. - bind: - $esManagerLive: '@es.manager.live' -``` - -In the twig template you can use the [ArticleViewDocument](article-view-document.md) to render for example a list of -articles. - -```twig -{% extends "base.html.twig" %} - -{% block content %} -

{{ content.title }}

- - - - -{% endblock %} -``` - -### Page-Tree-Route - -As an addition to the example above you can use the [page_tree_route](routing.md#page-tree-integration) to link articles -to a specific page. - -This can be handled in th controller by changing the `loadArticles($page, $pageSize, $structure->getUuid()`. - -```php -private function loadArticles($page, $pageSize, $uuid) -{ - $repository = $this->getRepository(); - $search = $repository->createSearch() - ->addSort(new FieldSort('authored', FieldSort::DESC)) - ->setFrom(($page - 1) * $pageSize) - ->setSize($pageSize) - ->addQuery(new TermQuery('parent_page_uuid', $uuid)); - - return $repository->findDocuments($search); -} -``` - -The rest of the code can be reused. diff --git a/Resources/doc/routing.md b/Resources/doc/routing.md deleted file mode 100644 index 6f43e18c3..000000000 --- a/Resources/doc/routing.md +++ /dev/null @@ -1,120 +0,0 @@ -# Routing - -The articles uses the routing-system of sulu. This enables entities (in this case the article) -to manage the routes centrally in the database. This routes will be used to determine which -Controller will be called during the request. - -This controller can be configured in the template file of the article. This xml-file contains -an item which is called `` and it contains the controller name (also services are -possible) and the action (or function) name. - -The arguments for the controller are: - -* `ArticleInterface $object`: The article itself. -* `string $view`: Contains the value of the `` node from the template.xml file. -* `int $pageNumber`: The page-number is used to pass tell the controller which page of the - article should be rendered. -* `int _cacheLifetime`: Contains the resolved value of `` node from the - template.xml file. - -Additionally the `Request $request` can also be used in the controller. - -## Route Schema - -The `route_schema` which will be used to generate a route for a newly created article can be -defined in the configuration. - -```yml -sulu_route: - mappings: - Sulu\Bundle\ArticleBundle\Document\ArticleDocument: - generator: schema - options: - route_schema: '/articles/{implode("-", object)}' -``` - -This schema will be used for all articles which will be created in the future. Older articles -will not be touched. - -### Overwrite route schema in template - -You can use a different `route_schema` for articles with a specific template by setting the -`route_schema` param of the `routePath` property in the template: - -```xml - - - Resourcelocator - Adresse - - - - - - - - -``` - -## Route Generation - -For the route generation this bundle provides two different ways and two different approaches. - -### Route Schema - -This method is default for SuluArticleBundle. It generates the route by a custom schema which is -already configured in the installation process (see [installation](installation.md)). - -To use this approach you have to do nothing (if you followed the installation description). For -the completeness you have to be aware that following steps are done: - -* The `routePath` property uses the `route` content type -* The `sulu_route` configuration includes a `route_schema` for the `ArticleDocument` - -### Page tree integration - -The other approach is based on the page-tree. You can choose a page which is used as the parent -route to generate the routes for the article (e.g. `/page/article`). Each article can have its -own parent-page and can so be coupled to the page. - -To use this approach you have to change the content-type of the property `routePath` to -`page_tree_route`. This will change the UI for this property in the Sulu-Admin and behind the -scenes the routes will be handled in a different way. - -```xml - - - Resourcelocator - Adresse - - -``` - -You still can define the rear part generation of the url like descripted above. - -**Route update** - -When changing a url of a page the system also update the routes of all the linked articles. -By default this behaviour will be called immediately on publishing the page. This could consume -a lot of time when lots of articles are linked to the saved page. - -To omit this the bundle provides a way to asynchronously call this route-update via the -SuluAutomationBundle. To enable it you have to install the -[SuluAutomationBundle](https://github.com/sulu/SuluAutomationBundle) and add following -configuration to `app/config/admin/config.yml`: - -```yaml -sulu_article: - content_types: - page_tree_route: - page_route_cascade: task # "request" or "off" -``` - -**Route move** - -When the parent-page of multiple articles should be changed (e.g. the page was removed) you can use following command to -update the parent-page of all articles which are related to the given page-url. - -```bash -bin/console sulu:article:page-tree:move /page-1 /page-2 sulu_io de -``` diff --git a/Resources/doc/twig-extensions.md b/Resources/doc/twig-extensions.md deleted file mode 100644 index 1ad1cff8e..000000000 --- a/Resources/doc/twig-extensions.md +++ /dev/null @@ -1,49 +0,0 @@ -# Twig Extensions - -Twig Extensions - -* Load recent articles: `sulu_article_load_recent` -* Load similar articles: `sulu_article_load_similar` - -## `sulu_article_load_recent` - -Returns recent published articles, filter by given parameters. - -### Arguments - -- **limit**: *integer* - optional: set the limit - default: 5 -- **types**: *array* - optional: filter for article types - default: type of the requested article or null -- **locale**: *string* - optional: filter for locale - default: locale of the request -- **ignoreWebspaces**: *bool* - ignore webspace settings - default: false - -### Returns - -The content-type returns a list of `ArticleResourceItem` instances. - -### Example - -```twig -{% set articles = sulu_article_load_recent(3, ['blog']) %} -``` - -## `sulu_article_load_similar` - -Returns similar articles compared to the requested one. -Note: Which fields are included in this request can be configured with `sulu_article.search_fields` config parameter. - -### Arguments - -- **limit**: *integer* - optional: set the limit - default: 5 -- **types**: *array* - optional: filter for article types - default: type of the requested article -- **locale**: *string* - optional: filter for locale - default: locale of the request -- **ignoreWebspaces**: *bool* - ignore webspace settings - default: false - -### Returns - -The content-type returns a list of `ArticleResourceItem` instances. - -### Example - -```twig -{% set articles = sulu_article_load_similar(5, ['blog']) %} -``` diff --git a/Resources/doc/xliff.md b/Resources/doc/xliff.md deleted file mode 100644 index 5b7c17c9f..000000000 --- a/Resources/doc/xliff.md +++ /dev/null @@ -1,50 +0,0 @@ -# XLIFF Export / Import - -The SuluArticleBundle is able to export the content of the articles into a XLIFF format. The resulting file can be used -by a translation tool or send to a translation agency. - -They can extend the file with the translation and after that imported by the developer. - -__Export:__ - -```bash -$ bin/adminconsole sulu:article:export export.xliff en - -Article Language Export -======================= - -Options -Target: export.xliff -Locale: en -Format: 1.2.xliff ---------------- - -Continue with this options?(y/n) y -Continue! -Loading Data… - 30/30 [============================] 100% -Render Xliff… -``` - -__Import:__ - -```bash -$ bin/adminconsole sulu:article:import export.xliff de --overrideSettings -Language Import -=============== - -Options -Locale: de -Format: 1.2.xliff -Override Setting: YES ---------------- - -Continue with this options? Be careful! (y/n) y -Continue! - 1/1 [============================] 100% 2 secs/2 secs 54.5 MiB - -Import Result -=============== -1 Documents imported. -0 Documents ignored. -``` diff --git a/Resources/phpcr-migrations/Version201702211450.php b/Resources/phpcr-migrations/Version201702211450.php deleted file mode 100644 index f4c5f82c4..000000000 --- a/Resources/phpcr-migrations/Version201702211450.php +++ /dev/null @@ -1,124 +0,0 @@ --authors` and adds `i18n:-author`. - */ -class Version201702211450 implements VersionInterface, ContainerAwareInterface -{ - use ContainerAwareTrait; - - public function up(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - /** - * Upgrade all nodes in given session. - */ - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE [jcr:mixinTypes] = "sulu:article"'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - /** @var Node $node */ - $node = $row->getNode(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - $value = null; - $authorsPropertyName = \sprintf('i18n:%s-authors', $localization->getLocale()); - if ($node->hasProperty($authorsPropertyName)) { - $property = $node->getProperty($authorsPropertyName); - $value = $property->getValue(); - if (\is_array($value) && \count($value) > 0) { - $value = $value[0]; - } - $property->remove(); - } - $authorPropertyName = \sprintf('i18n:%s-author', $localization->getLocale()); - if (!$node->hasProperty($authorPropertyName)) { - $node->setProperty( - $authorPropertyName, - $value - ); - } - } - } - } - - /** - * Downgrades all nodes in given session. - */ - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE [jcr:mixinTypes] = "sulu:article"'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - $node = $row->getNode(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - $value = null; - $authorPropertyName = \sprintf('i18n:%s-author', $localization->getLocale()); - if ($node->hasProperty($authorPropertyName)) { - $property = $node->getProperty($authorPropertyName); - $value = $property->getValue(); - $property->remove(); - } - $authorsPropertyName = \sprintf('i18n:%s-authors', $localization->getLocale()); - if (!$node->hasProperty($authorsPropertyName)) { - $node->setProperty( - $authorsPropertyName, - [$value] - ); - } - } - } - } -} diff --git a/Resources/phpcr-migrations/Version201712041018.php b/Resources/phpcr-migrations/Version201712041018.php deleted file mode 100644 index 5bf639bb4..000000000 --- a/Resources/phpcr-migrations/Version201712041018.php +++ /dev/null @@ -1,160 +0,0 @@ --author(ed)`. - */ -class Version201712041018 implements VersionInterface, ContainerAwareInterface -{ - use ContainerAwareTrait; - - public const AUTHOR_PROPERTY_NAME = 'sulu:author'; - - public const AUTHORED_PROPERTY_NAME = 'sulu:authored'; - - public function up(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - /** - * Upgrade all nodes in given session. - */ - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE [jcr:mixinTypes] = "sulu:article"'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - /** @var Node $node */ - $node = $row->getNode(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - if (!$node->hasProperty(\sprintf('i18n:%s-template', $localization->getLocale()))) { - continue; - } - - $this->upgradeAuthor($node, $localization->getLocale()); - $this->upgradeAuthored($node, $localization->getLocale()); - } - - if ($node->hasProperty(self::AUTHOR_PROPERTY_NAME)) { - $node->getProperty(self::AUTHOR_PROPERTY_NAME)->remove(); - } - if ($node->hasProperty(self::AUTHORED_PROPERTY_NAME)) { - $node->getProperty(self::AUTHORED_PROPERTY_NAME)->remove(); - } - } - } - - private function upgradeAuthor(NodeInterface $node, $locale) - { - if (!$node->hasProperty(self::AUTHOR_PROPERTY_NAME)) { - return; - } - - $authorPropertyName = \sprintf('i18n:%s-author', $locale); - $node->setProperty($authorPropertyName, $node->getPropertyValue(self::AUTHOR_PROPERTY_NAME)); - } - - private function upgradeAuthored(NodeInterface $node, $locale) - { - if (!$node->hasProperty(self::AUTHORED_PROPERTY_NAME)) { - return; - } - - $authoredPropertyName = \sprintf('i18n:%s-authored', $locale); - $node->setProperty($authoredPropertyName, $node->getPropertyValue(self::AUTHORED_PROPERTY_NAME)); - } - - /** - * Downgrades all nodes in given session. - */ - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE [jcr:mixinTypes] = "sulu:article"'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - /** @var Node $node */ - $node = $row->getNode(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - if (!$node->hasProperty(\sprintf('i18n:%s-changed', $localization->getLocale()))) { - continue; - } - - $this->downgradeAuthor($node, $localization->getLocale()); - $this->downgradeAuthored($node, $localization->getLocale()); - } - } - } - - private function downgradeAuthor(NodeInterface $node, $locale) - { - $authorPropertyName = \sprintf('i18n:%s-author', $locale); - if (!$node->hasProperty($authorPropertyName)) { - return; - } - - $node->setProperty(self::AUTHOR_PROPERTY_NAME, $node->getPropertyValue($authorPropertyName)); - $node->getProperty($authorPropertyName)->remove(); - } - - private function downgradeAuthored(NodeInterface $node, $locale) - { - $authoredPropertyName = \sprintf('i18n:%s-authored', $locale); - if (!$node->hasProperty($authoredPropertyName)) { - return; - } - - $node->setProperty(self::AUTHORED_PROPERTY_NAME, $node->getPropertyValue($authoredPropertyName)); - $node->getProperty($authoredPropertyName)->remove(); - } -} diff --git a/Resources/phpcr-migrations/Version201811091000.php b/Resources/phpcr-migrations/Version201811091000.php deleted file mode 100644 index c7942618a..000000000 --- a/Resources/phpcr-migrations/Version201811091000.php +++ /dev/null @@ -1,183 +0,0 @@ --mainWebspace`. - * Removes the property `additionalWebspaces` and adds `i18n:-additionalWebspaces`. - */ -class Version201811091000 implements VersionInterface, ContainerAwareInterface -{ - use ContainerAwareTrait; - - public const MAIN_WEBSPACE_PROPERTY_NAME = 'mainWebspace'; - - public const ADDITONAL_WEBSPACES_PROPERTY_NAME = 'additionalWebspaces'; - - public function up(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - /** - * Upgrade all nodes in given session. - */ - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE [jcr:mixinTypes] = "sulu:article"'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - /** @var Node $node */ - $node = $row->getNode(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - // check if node exists - if (!$node->hasProperty(\sprintf('i18n:%s-template', $localization->getLocale()))) { - continue; - } - - $this->upgradeMainWebspace($node, $localization->getLocale()); - $this->upgradeAdditionalWebspaces($node, $localization->getLocale()); - } - - if ($node->hasProperty(self::MAIN_WEBSPACE_PROPERTY_NAME)) { - $node->getProperty(self::MAIN_WEBSPACE_PROPERTY_NAME)->remove(); - } - if ($node->hasProperty(self::ADDITONAL_WEBSPACES_PROPERTY_NAME)) { - $node->getProperty(self::ADDITONAL_WEBSPACES_PROPERTY_NAME)->remove(); - } - } - } - - private function upgradeMainWebspace(NodeInterface $node, $locale) - { - if (!$node->hasProperty(self::MAIN_WEBSPACE_PROPERTY_NAME)) { - return; - } - - $value = $node->getPropertyValue(self::MAIN_WEBSPACE_PROPERTY_NAME); - if ($value) { - $mainWebspacePropertyNameLocalized = \sprintf('i18n:%s-' . self::MAIN_WEBSPACE_PROPERTY_NAME, $locale); - $node->setProperty( - $mainWebspacePropertyNameLocalized, - $node->getPropertyValue(self::MAIN_WEBSPACE_PROPERTY_NAME) - ); - } - } - - private function upgradeAdditionalWebspaces(NodeInterface $node, $locale) - { - if (!$node->hasProperty(self::ADDITONAL_WEBSPACES_PROPERTY_NAME)) { - return; - } - - $value = $node->getPropertyValue(self::ADDITONAL_WEBSPACES_PROPERTY_NAME); - if ($value) { - $additionalWebspacesPropertyNameLocalized = \sprintf('i18n:%s-' . self::ADDITONAL_WEBSPACES_PROPERTY_NAME, $locale); - $node->setProperty( - $additionalWebspacesPropertyNameLocalized, - $value - ); - } - } - - /** - * Downgrades all nodes in given session. - */ - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE [jcr:mixinTypes] = "sulu:article"'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - /** @var Node $node */ - $node = $row->getNode(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - // check if node exists - if (!$node->hasProperty(\sprintf('i18n:%s-template', $localization->getLocale()))) { - continue; - } - - $this->downgradeMainWebspace($node, $localization->getLocale()); - $this->downgradeAdditionalWebspaces($node, $localization->getLocale()); - } - } - } - - private function downgradeMainWebspace(NodeInterface $node, $locale) - { - $mainWebspacePropertyNameLocalized = \sprintf('i18n:%s-' . self::MAIN_WEBSPACE_PROPERTY_NAME, $locale); - if (!$node->hasProperty($mainWebspacePropertyNameLocalized)) { - return; - } - - $value = $node->getPropertyValue($mainWebspacePropertyNameLocalized); - if ($value) { - $node->setProperty(self::MAIN_WEBSPACE_PROPERTY_NAME, $value); - } - - $node->getProperty($mainWebspacePropertyNameLocalized)->remove(); - } - - private function downgradeAdditionalWebspaces(NodeInterface $node, $locale) - { - $additionalWebspacesPropertyNameLocalized = \sprintf('i18n:%s-' . self::ADDITONAL_WEBSPACES_PROPERTY_NAME, $locale); - if (!$node->hasProperty($additionalWebspacesPropertyNameLocalized)) { - return; - } - - $value = $node->getPropertyValue($additionalWebspacesPropertyNameLocalized); - if ($value) { - $node->setProperty(self::ADDITONAL_WEBSPACES_PROPERTY_NAME, $value); - } - - $node->getProperty($additionalWebspacesPropertyNameLocalized)->remove(); - } -} diff --git a/Resources/phpcr-migrations/Version201905071542.php b/Resources/phpcr-migrations/Version201905071542.php deleted file mode 100644 index 9040450b3..000000000 --- a/Resources/phpcr-migrations/Version201905071542.php +++ /dev/null @@ -1,97 +0,0 @@ -container->get('sulu_document_manager.live_session'); - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:page" OR [jcr:mixinTypes] = "sulu:home")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - if (\is_array($propertyValue) && \array_key_exists('items', $propertyValue)) { - foreach ($propertyValue['items'] as &$item) { - if (isset($item['type']) && 'article' === $item['type']) { - $item['type'] = 'articles'; - } - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } - - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:page" OR [jcr:mixinTypes] = "sulu:home")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - if (\is_array($propertyValue) && \array_key_exists('items', $propertyValue)) { - foreach ($propertyValue['items'] as &$item) { - if (isset($item['type']) && 'articles' === $item['type']) { - $item['type'] = 'article'; - } - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } -} diff --git a/Resources/phpcr-migrations/Version202005151141.php b/Resources/phpcr-migrations/Version202005151141.php deleted file mode 100644 index f649ba2da..000000000 --- a/Resources/phpcr-migrations/Version202005151141.php +++ /dev/null @@ -1,103 +0,0 @@ -container->get('sulu_document_manager.live_session'); - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:page" OR [jcr:mixinTypes] = "sulu:home" OR [jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - if (\is_array($propertyValue) && \array_key_exists('items', $propertyValue)) { - foreach ($propertyValue['items'] as &$item) { - if (isset($item['type']) && 'article' === $item['type']) { - $item['type'] = 'articles'; - } - if (isset($item['type']) && 'content' === $item['type']) { - $item['type'] = 'pages'; - } - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } - - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:page" OR [jcr:mixinTypes] = "sulu:home" OR [jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - if (\is_array($propertyValue) && \array_key_exists('items', $propertyValue)) { - foreach ($propertyValue['items'] as &$item) { - if (isset($item['type']) && 'articles' === $item['type']) { - $item['type'] = 'article'; - } - if (isset($item['type']) && 'pages' === $item['type']) { - $item['type'] = 'content'; - } - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } -} diff --git a/Resources/phpcr-migrations/Version202005191117.php b/Resources/phpcr-migrations/Version202005191117.php deleted file mode 100644 index 40880d39e..000000000 --- a/Resources/phpcr-migrations/Version202005191117.php +++ /dev/null @@ -1,97 +0,0 @@ -container->get('sulu_document_manager.live_session'); - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:snippet")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - if (\is_array($propertyValue) && \array_key_exists('items', $propertyValue)) { - foreach ($propertyValue['items'] as &$item) { - if (isset($item['type']) && 'article' === $item['type']) { - $item['type'] = 'articles'; - } - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } - - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:snippet")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - if (\is_array($propertyValue) && \array_key_exists('items', $propertyValue)) { - foreach ($propertyValue['items'] as &$item) { - if (isset($item['type']) && 'articles' === $item['type']) { - $item['type'] = 'article'; - } - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } -} diff --git a/Resources/phpcr-migrations/Version202005250920.php b/Resources/phpcr-migrations/Version202005250920.php deleted file mode 100644 index b50a80926..000000000 --- a/Resources/phpcr-migrations/Version202005250920.php +++ /dev/null @@ -1,97 +0,0 @@ -container->get('sulu_document_manager.live_session'); - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - - // decide if property is of type smart_content type by checking for presentAs and sortBy - if (\is_array($propertyValue) && \array_key_exists('presentAs', $propertyValue) && \array_key_exists('sortBy', $propertyValue)) { - if (\is_array($propertyValue['sortBy'])) { - $propertyValue['sortBy'] = \count($propertyValue['sortBy']) > 0 ? $propertyValue['sortBy'][0] : null; - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } - - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - if (\is_string($property->getValue())) { - $propertyValue = \json_decode($property->getValue(), true); - - // decide if property is of type smart_content type by checking for presentAs and sortBy - if (\is_array($propertyValue) && \array_key_exists('presentAs', $propertyValue) && \array_key_exists('sortBy', $propertyValue)) { - if (!\is_array($propertyValue['sortBy'])) { - $propertyValue['sortBy'] = [$propertyValue['sortBy']]; - } - - $property->setValue(\json_encode($propertyValue)); - } - } - } - } - } -} diff --git a/Resources/phpcr-migrations/Version202210140922.php b/Resources/phpcr-migrations/Version202210140922.php deleted file mode 100644 index 0c61c814e..000000000 --- a/Resources/phpcr-migrations/Version202210140922.php +++ /dev/null @@ -1,129 +0,0 @@ -container->get('sulu_document_manager.live_session'); - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - $propertyValue = $property->getValue(); - - if (\is_string($propertyValue)) { - if (false !== \strpos($propertyValue, '(.*?)<\/sulu:media>/', - function($match) { - return '' - . $match[2] - . ''; - }, - $propertyValue - ); - } - - if (false !== \strpos($propertyValue, '(.*?)<\/sulu:(.*?)>/', - '$3', - $propertyValue - ); - } - - if ($propertyValue !== $property->getValue()) { - $property->setValue($propertyValue); - } - } - } - } - } - - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - foreach ($rows as $row) { - $node = $row->getNode(); - - foreach ($node->getProperties() as $property) { - $propertyValue = $property->getValue(); - - if (\is_string($propertyValue)) { - if (false !== \strpos($propertyValue, '(.*?)<\/sulu-link>/', - function($match) { - return '' . $match[2] . ''; - }, - $propertyValue - ); - } - - if (false !== \strpos($propertyValue, '(.*?)<\/sulu-(.*?)>/', - '$3', - $propertyValue - ); - } - - if ($propertyValue !== $property->getValue()) { - $property->setValue($propertyValue); - } - } - } - } - } -} diff --git a/Resources/phpcr-migrations/Version202210241106.php b/Resources/phpcr-migrations/Version202210241106.php deleted file mode 100644 index 0f7403b90..000000000 --- a/Resources/phpcr-migrations/Version202210241106.php +++ /dev/null @@ -1,109 +0,0 @@ -container->get('sulu_document_manager.live_session'); - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $liveSession = $this->container->get('sulu_document_manager.live_session'); - - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - private function upgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - $suffixPropertyName = \sprintf('i18n:%s-routePath-suffix', $localization->getLocale()); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - $node = $row->getNode(); - - if (!$node || !$node->hasProperty($suffixPropertyName)) { - continue; - } - - $suffix = $node->getPropertyValue($suffixPropertyName); - $newSuffix = '/' . \ltrim($suffix, '/'); - - if ($suffix === $newSuffix) { - continue; - } - - $node->setProperty($suffixPropertyName, $newSuffix); - } - } - } - - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - $suffixPropertyName = \sprintf('i18n:%s-routePath-suffix', $localization->getLocale()); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Row $row */ - foreach ($rows as $row) { - $node = $row->getNode(); - - if (!$node || !$node->hasProperty($suffixPropertyName)) { - continue; - } - - $suffix = $node->getPropertyValue($suffixPropertyName); - $newSuffix = \ltrim($suffix, '/'); - - if ($suffix === $newSuffix) { - continue; - } - - $node->setProperty($suffixPropertyName, $newSuffix); - } - } - } -} diff --git a/Resources/phpcr-migrations/Version202407111600.php b/Resources/phpcr-migrations/Version202407111600.php deleted file mode 100644 index 1d996f345..000000000 --- a/Resources/phpcr-migrations/Version202407111600.php +++ /dev/null @@ -1,137 +0,0 @@ -container = $container; - } - - public function up(SessionInterface $session) - { - $this->propertyEncoder = $this->container->get('sulu_document_manager.property_encoder'); - $this->metadataFactory = $this->container->get('sulu_page.structure.factory'); - - $liveSession = $this->container->get('sulu_document_manager.live_session'); - $this->upgrade($liveSession); - $this->upgrade($session); - - $liveSession->save(); - $session->save(); - } - - public function down(SessionInterface $session) - { - $this->propertyEncoder = $this->container->get('sulu_document_manager.property_encoder'); - $this->metadataFactory = $this->container->get('sulu_page.structure.factory'); - - $liveSession = $this->container->get('sulu_document_manager.live_session'); - $this->downgrade($liveSession); - $this->downgrade($session); - - $liveSession->save(); - $session->save(); - } - - private function upgrade(SessionInterface $session): void - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - $locale = $localization->getLocale(); - $templateKey = $this->propertyEncoder->localizedContentName('template', $locale); - - /** @var Row $row */ - foreach ($rows as $row) { - $node = $row->getNode(); - $structureType = $node->getPropertyValue($templateKey); - $routePathPropertyName = $this->getRoutePathPropertyName($structureType, $locale); - - $propertyName = $this->propertyEncoder->localizedContentName(RoutableSubscriber::ROUTE_FIELD_NAME, $locale); - $node->setProperty($propertyName, $routePathPropertyName); - } - } - } - - private function downgrade(SessionInterface $session) - { - $queryManager = $session->getWorkspace()->getQueryManager(); - $localizations = $this->container->get('sulu_core.webspace.webspace_manager')->getAllLocalizations(); - - $query = 'SELECT * FROM [nt:unstructured] WHERE ([jcr:mixinTypes] = "sulu:article" OR [jcr:mixinTypes] = "sulu:articlepage")'; - $rows = $queryManager->createQuery($query, 'JCR-SQL2')->execute(); - - /** @var Localization $localization */ - foreach ($localizations as $localization) { - $locale = $localization->getLocale(); - - /** @var Row $row */ - foreach ($rows as $row) { - $node = $row->getNode(); - $propertyName = $this->propertyEncoder->localizedContentName(RoutableSubscriber::ROUTE_FIELD_NAME, $locale); - $node->setProperty($propertyName, null); - } - } - } - - private function getRoutePathPropertyName(string $structureType, string $locale): string - { - $metadata = $this->metadataFactory->getStructureMetadata('article', $structureType); - - if ($metadata->hasPropertyWithTagName(RoutableSubscriber::TAG_NAME)) { - return $this->getPropertyName($locale, $metadata->getPropertyByTagName(RoutableSubscriber::TAG_NAME)->getName()); - } - - return $this->getPropertyName($locale, RoutableSubscriber::ROUTE_FIELD); - } - - private function getPropertyName(string $locale, string $field): string - { - return $this->propertyEncoder->localizedSystemName($field, $locale); - } -} diff --git a/Resources/views/Export/Article/1.2.xliff.twig b/Resources/views/Export/Article/1.2.xliff.twig deleted file mode 100644 index c92ed0979..000000000 --- a/Resources/views/Export/Article/1.2.xliff.twig +++ /dev/null @@ -1,42 +0,0 @@ -{% extends "@SuluArticle/Export/Article/base.export.twig" %} - -{% block main %} - - -{{ parent() }} - -{% endblock main %} - -{% block article %} - - - {{- parent() -}} - - -{% endblock article %} - -{# view #} -{%- block view -%} - {% apply spaceless %} - {% set attributes = '' %} - {% set target = '' %} - {%- if value is iterable -%} - {% set value = value|json_encode %} - {%- endif -%} - {%- if options.translate is defined and not options.translate -%} - {% set attributes = attributes ~ ' translate="no"' %} - {% set target = value %} - {%- endif -%} - {% if type == 'text_editor' %} - {% set attributes = attributes ~ ' datatype="html"' %} - {% endif %} - {% endapply %} - {% autoescape false %} - - - - {{ sulu_content_type_export_escape(value) }} - {{ sulu_content_type_export_escape(target) }} - - {% endautoescape %} -{%- endblock view -%} diff --git a/Resources/views/Export/Article/base.export.twig b/Resources/views/Export/Article/base.export.twig deleted file mode 100644 index 77de5e7f0..000000000 --- a/Resources/views/Export/Article/base.export.twig +++ /dev/null @@ -1,77 +0,0 @@ -{% block main %} - {{ block('articles') }} -{% endblock main %} - -{% if false %} {# avoid output of block directly #} - {# Iterate over the articles #} - {%- block articles -%} - {%- for document in documents -%} - {% apply spaceless %} - {% set settings = document.settings %} - {% set content = document.content %} - {% set extensions = document.extensions %} - {% set prefix = '' %} - {% endapply %}{{ block('article') }} - {%- endfor -%} - {%- endblock articles -%} - - {% block article %} - {{- block('content') -}} - {{- block('extensions') -}} - {{- block('settings') -}} - {% endblock article %} - - {# Output content #} - {%- block content -%} - {% set properties = content %} - {{- block('properties') -}} - {%- endblock content -%} - - {# Output extensions #} - {%- block extensions -%} - {%- for key, extension in extensions -%} - {% set prefixBefore = prefix %} - {% set prefix = prefix ~ key ~ '-' %} - {% set properties = extension %} - {{- block('properties') -}} - {% set prefix = prefixBefore %} - {%- endfor -%} - {%- endblock extensions -%} - - {# Output settings #} - {%- block settings -%} - {% set properties = settings %} - {{- block('properties') -}} - {%- endblock settings -%} - - {# Output properties #} - {%- block properties -%} - {%- for property in properties -%} - {% if property.value is defined %} - {{- block('model') -}} - {% endif %} - {%- if property.children is defined -%} - {%- for key, child in property.children -%} - {% set prefixBefore = prefix %} - {% set prefix = prefix ~ property.name ~ '#' ~ key ~ '-' %} - {% set properties = child %} - {{- block('properties') -}} - {% set prefix = prefixBefore %} - {%- endfor -%} - {%- endif -%} - {%- endfor -%} - {%- endblock properties -%} - - {# Output model #} - {%- block model -%} - {% apply spaceless %} - {% set name = prefix ~ property.name %} - {% set options = property.options|default('') %} - {% set value = property.value %} - {% set type = property.type|default('') %} - {% endapply %}{{- block('view') -}} - {%- endblock model -%} - - {# View #} - {%- block view -%}{%- endblock view -%} -{% endif %} diff --git a/Routing/ArticlePageRouteGenerator.php b/Routing/ArticlePageRouteGenerator.php deleted file mode 100644 index 3a326c9e4..000000000 --- a/Routing/ArticlePageRouteGenerator.php +++ /dev/null @@ -1,66 +0,0 @@ -routeGenerator = $routeGenerator; - $this->tokenProvider = $tokenProvider; - } - - public function generate($entity, array $options) - { - $parent = $options['parent']; - - $tokens = []; - \preg_match_all('/{(.*?)}/', $parent, $matches); - $tokenNames = $matches[1]; - - foreach ($tokenNames as $name) { - $tokenName = '{' . $name . '}'; - $tokenValue = $this->tokenProvider->provide($entity, $name); - - $tokens[$tokenName] = $tokenValue; - } - - $parentPath = \strtr($parent, $tokens); - - return $this->routeGenerator->generate($entity, ['route_schema' => $parentPath . $options['route_schema']]); - } - - public function getOptionsResolver(array $options) - { - return (new OptionsResolver())->setRequired(['route_schema', 'parent']); - } -} diff --git a/Routing/ArticleRouteDefaultProvider.php b/Routing/ArticleRouteDefaultProvider.php deleted file mode 100644 index 71237175e..000000000 --- a/Routing/ArticleRouteDefaultProvider.php +++ /dev/null @@ -1,195 +0,0 @@ -documentManager = $documentManager; - $this->structureMetadataFactory = $structureMetadataFactory; - $this->cacheLifetimeResolver = $cacheLifetimeResolver; - $this->structureManager = $structureManager; - $this->webspaceResolver = $webspaceResolver; - $this->requestAnalyzer = $requestAnalyzer; - } - - /** - * @param ArticleDocument $object - */ - public function getByEntity($entityClass, $id, $locale, $object = null) - { - if (!$object) { - $object = $this->documentManager->find($id, $locale); - } - - $pageNumber = $object->getPageNumber(); - if ($object instanceof ArticlePageDocument) { - // the article contains the seo/excerpt data and the controller handles the page-number automatically - /** @var ArticleDocument $object */ - $object = $object->getParent(); - } - - $metadata = $this->structureMetadataFactory->getStructureMetadata('article', $object->getStructureType()); - - // this parameter should not be used - // but the sulu-collector for the profiler needs it to determine data from request - /** @var StructureBridge $structure */ - $structure = $this->structureManager->wrapStructure('article', $metadata); - $structure->setDocument($object); - - return [ - 'object' => $object, - 'view' => $metadata->getView(), - 'pageNumber' => $pageNumber, - 'structure' => $structure, - '_cacheLifetime' => $this->getCacheLifetime($metadata), - '_controller' => $metadata->getController(), - ]; - } - - /** - * If article is not published the document will be of typ unknown-document. - * Also check the workflow stage if it`s a ArticleDocument. - * - * {@inheritdoc} - */ - public function isPublished($entityClass, $id, $locale) - { - $object = $this->documentManager->find( - $id, - $locale, - [ - 'load_ghost_content' => false, - ] - ); - - if (!$object instanceof ArticleInterface) { - return false; - } - - if ($object instanceof ShadowLocaleBehavior && $object->isShadowLocaleEnabled()) { - $object = $this->documentManager->find( - $id, - $object->getShadowLocale(), - [ - 'load_ghost_content' => false, - ], - ); - } - - if (!$object instanceof ArticleInterface || WorkflowStage::PUBLISHED !== $object->getWorkflowStage()) { - return false; - } - - if (!$object instanceof WebspaceBehavior) { - return true; - } - - $webspace = $this->requestAnalyzer->getWebspace(); - if (!$webspace - || ( - $this->webspaceResolver->resolveMainWebspace($object) !== $webspace->getKey() - && !\in_array($webspace->getKey(), $this->webspaceResolver->resolveAdditionalWebspaces($object)) - ) - ) { - return false; - } - - return true; - } - - public function supports($entityClass) - { - return ArticleDocument::class === $entityClass - || ArticlePageDocument::class === $entityClass - || \is_subclass_of($entityClass, ArticleDocument::class) - || \is_subclass_of($entityClass, ArticlePageDocument::class); - } - - /** - * Get cache life time. - */ - private function getCacheLifetime(StructureMetadata $metadata): ?int - { - $cacheLifetime = $metadata->getCacheLifetime(); - - if (!$cacheLifetime) { - return null; - } - - if (!\is_array($cacheLifetime) - || !isset($cacheLifetime['type']) - || !isset($cacheLifetime['value']) - || !$this->cacheLifetimeResolver->supports($cacheLifetime['type'], $cacheLifetime['value']) - ) { - throw new \InvalidArgumentException(\sprintf('Invalid cachelifetime in article route default provider: %s', \var_export($cacheLifetime, true))); - } - - return $this->cacheLifetimeResolver->resolve($cacheLifetime['type'], $cacheLifetime['value']); - } -} diff --git a/Routing/ArticleRouteEnhancer.php b/Routing/ArticleRouteEnhancer.php deleted file mode 100644 index 37651d41a..000000000 --- a/Routing/ArticleRouteEnhancer.php +++ /dev/null @@ -1,104 +0,0 @@ -webspaceManager = $webspaceManager; - $this->webspaceResolver = $webspaceResolver; - $this->environment = $environment; - } - - public function enhance(array $defaults, Request $request): array - { - if (!$this->shouldAddCanonicalTag($defaults, $request)) { - return $defaults; - } - - $article = $defaults['object']; - $seo['canonicalUrl'] = $this->webspaceManager->findUrlByResourceLocator( - $article->getRoutePath(), - $this->environment, - $article->getLocale(), - $this->webspaceResolver->resolveMainWebspace($article) - ); - - return \array_merge( - $defaults, - ['_seo' => $seo] - ); - } - - /** - * Checks if the enhancer should add an canonical tag to the route attributes. - */ - private function shouldAddCanonicalTag(array $defaults, Request $request): bool - { - if (!\array_key_exists('object', $defaults)) { - return false; - } - - $article = $defaults['object']; - if (!$article instanceof ArticleInterface || !$article instanceof WebspaceBehavior) { - return false; - } - - $sulu = $request->get('_sulu'); - if (!$sulu) { - return false; - } - - /** @var Webspace $webspace */ - $webspace = $sulu->getAttribute('webspace'); - if (!$webspace) { - return false; - } - - $additionalWebspaces = $this->webspaceResolver->resolveAdditionalWebspaces($article); - if (!$additionalWebspaces || !\in_array($webspace->getKey(), $additionalWebspaces)) { - return false; - } - - return true; - } -} diff --git a/Routing/ArticleRouteGeneratorByTemplate.php b/Routing/ArticleRouteGeneratorByTemplate.php deleted file mode 100644 index 0c239a09d..000000000 --- a/Routing/ArticleRouteGeneratorByTemplate.php +++ /dev/null @@ -1,55 +0,0 @@ -routeGenerator = $routeGenerator; - } - - /** - * @param ArticleDocument $entity - */ - public function generate($entity, array $options) - { - $template = $entity->getStructureType(); - - if (!\array_key_exists($template, $options)) { - throw new RouteSchemaNotFoundException($template, \array_keys($options)); - } - - return $this->routeGenerator->generate($entity, ['route_schema' => $options[$template]]); - } - - public function getOptionsResolver(array $options) - { - return (new OptionsResolver())->setDefined(\array_keys($options)); - } -} diff --git a/Routing/ArticleRouteGeneratorByType.php b/Routing/ArticleRouteGeneratorByType.php deleted file mode 100644 index ac181c68e..000000000 --- a/Routing/ArticleRouteGeneratorByType.php +++ /dev/null @@ -1,66 +0,0 @@ -routeGenerator = $routeGenerator; - $this->structureMetadataFactory = $structureMetadataFactory; - } - - /** - * @param ArticleDocument $entity - */ - public function generate($entity, array $options) - { - $type = $this->getType( - $this->structureMetadataFactory->getStructureMetadata('article', $entity->getStructureType()) - ); - - if (!\array_key_exists($type, $options)) { - throw new RouteSchemaNotFoundException($type, \array_keys($options)); - } - - return $this->routeGenerator->generate($entity, ['route_schema' => $options[$type]]); - } - - public function getOptionsResolver(array $options) - { - return (new OptionsResolver())->setDefined(\array_keys($options)); - } -} diff --git a/Search/ArticleSearchSubscriber.php b/Search/ArticleSearchSubscriber.php deleted file mode 100644 index 27edba598..000000000 --- a/Search/ArticleSearchSubscriber.php +++ /dev/null @@ -1,79 +0,0 @@ -factory = $factory; - $this->webspaceResolver = $webspaceResolver; - } - - /** - * {@inheritdoc} - * - * Returns the events this subscriber has subscribed. - */ - public static function getSubscribedEvents() - { - return [ - SearchEvents::PRE_INDEX => 'handlePreIndex', - ]; - } - - public function handlePreIndex(PreIndexEvent $event): void - { - $subject = $event->getSubject(); - $document = $event->getDocument(); - - if (!$subject instanceof ArticleDocument) { - return; - } - - $document->setUrl($subject->getRoutePath()); - - $document->addField( - $this->factory->createField( - 'mainWebspace', - $this->webspaceResolver->resolveMainWebspace($subject), - Field::TYPE_STRING - ) - ); - - $document->addField( - $this->factory->createField( - 'additionalWebspaces', - $this->webspaceResolver->resolveAdditionalWebspaces($subject), - Field::TYPE_ARRAY - ) - ); - } -} diff --git a/Sitemap/ArticleSitemapProvider.php b/Sitemap/ArticleSitemapProvider.php deleted file mode 100644 index ee60a7e94..000000000 --- a/Sitemap/ArticleSitemapProvider.php +++ /dev/null @@ -1,223 +0,0 @@ -manager = $manager; - $this->documentFactory = $documentFactory; - $this->webspaceManager = $webspaceManager; - } - - public function build($page, $scheme, $host) - { - $repository = $this->manager->getRepository($this->documentFactory->getClass('article')); - - $webspaceKeys = $this->getWebspaceKeysByHost($host); - - $result = []; - $from = 0; - $size = 1000; - - do { - $bulk = $this->getBulk($repository, $webspaceKeys, $from, $size); - /** @var SitemapUrl[] $sitemapUrlListByUuid */ - $sitemapUrlListByUuid = []; - - /** @var ArticleViewDocumentInterface $item */ - foreach ($bulk as $item) { - // Get all webspace keys which are for the current document and current selected webspaces - $itemWebspaceKeys = \array_intersect( - \array_merge([$item->getMainWebspace()], $item->getAdditionalWebspaces()), - $webspaceKeys - ); - - foreach ($itemWebspaceKeys as $itemWebspaceKey) { - $url = $this->buildUrl($item, $scheme, $host, $itemWebspaceKey); - - $result[] = $url; - - $alternativeUrlsKey = $itemWebspaceKey . '__' . $item->getUuid(); - if (!isset($sitemapUrlListByUuid[$alternativeUrlsKey])) { - $sitemapUrlListByUuid[$alternativeUrlsKey] = []; - } - - $sitemapUrlListByUuid[$alternativeUrlsKey] = $this->setAlternatives( - $sitemapUrlListByUuid[$alternativeUrlsKey], - $url - ); - } - } - - $from += $size; - } while ($bulk->count() > $from && $from < static::PAGE_SIZE); - - return $result; - } - - protected function buildUrl( - ArticleViewDocumentInterface $articleView, - string $scheme, - string $host, - string $webspaceKey - ): SitemapUrl { - return new SitemapUrl( - $this->findUrl($articleView, $scheme, $host, $webspaceKey), - $articleView->getLocale(), - null, - $articleView->getLastModified() ?? $articleView->getChanged() - ); - } - - private function findUrl( - ArticleViewDocumentInterface $articleView, - string $scheme, - string $host, - string $webspaceKey - ): string { - return $this->webspaceManager->findUrlByResourceLocator( - $articleView->getRoutePath(), - null, - $articleView->getLocale(), - $webspaceKey, - $host, - $scheme - ); - } - - /** - * Set alternatives to sitemap url. - * - * @param SitemapUrl[] $sitemapUrlList - * - * @return SitemapUrl[] - */ - private function setAlternatives(array $sitemapUrlList, SitemapUrl $sitemapUrl): array - { - foreach ($sitemapUrlList as $sitemapUrlFromList) { - // Add current as alternative to exist. - $sitemapUrlFromList->addAlternateLink( - new SitemapAlternateLink($sitemapUrl->getLoc(), $sitemapUrl->getLocale()) - ); - - // Add others as alternative to current. - $sitemapUrl->addAlternateLink( - new SitemapAlternateLink($sitemapUrlFromList->getLoc(), $sitemapUrlFromList->getLocale()) - ); - } - - $sitemapUrlList[] = $sitemapUrl; - - return $sitemapUrlList; - } - - private function getBulk(Repository $repository, array $webspaceKeys, int $from, int $size): DocumentIterator - { - $search = $repository->createSearch() - ->addQuery(new TermQuery('seo.hide_in_sitemap', 'false')) - ->setFrom($from) - ->setSize($size); - - $webspaceQuery = new BoolQuery(); - foreach ($webspaceKeys as $webspaceKey) { - $webspaceQuery->add(new TermQuery('main_webspace', $webspaceKey), BoolQuery::SHOULD); - $webspaceQuery->add(new TermQuery('additional_webspaces', $webspaceKey), BoolQuery::SHOULD); - } - - $search->addQuery($webspaceQuery); - if (\method_exists($search, 'setTrackTotalHits')) { - $search->setTrackTotalHits(true); - } - - return $repository->findDocuments($search); - } - - public function createSitemap($scheme, $host) - { - return new Sitemap($this->getAlias(), $this->getMaxPage($scheme, $host)); - } - - public function getMaxPage($schema, $host) - { - $repository = $this->manager->getRepository($this->documentFactory->getClass('article')); - $search = $repository->createSearch() - ->addQuery(new TermQuery('seo.hide_in_sitemap', 'false')); - - $webspaceKeys = $this->getWebspaceKeysByHost($host); - - $webspaceQuery = new BoolQuery(); - foreach ($webspaceKeys as $webspaceKey) { - $webspaceQuery->add(new TermQuery('main_webspace', $webspaceKey), BoolQuery::SHOULD); - $webspaceQuery->add(new TermQuery('additional_webspaces', $webspaceKey), BoolQuery::SHOULD); - } - - $search->addQuery($webspaceQuery); - - return \ceil($repository->count($search) / static::PAGE_SIZE); - } - - /** - * @return string[] - */ - private function getWebspaceKeysByHost(string $host): array - { - $portalInformations = $this->webspaceManager->findPortalInformationsByHostIncludingSubdomains($host); - - $webspaceKeys = []; - foreach ($portalInformations as $portalInformation) { - $webspaceKeys[] = $portalInformation->getWebspaceKey(); - } - - return $webspaceKeys; - } - - public function getAlias() - { - return 'articles'; - } -} diff --git a/Teaser/ArticleTeaserProvider.php b/Teaser/ArticleTeaserProvider.php deleted file mode 100644 index e95bfcb05..000000000 --- a/Teaser/ArticleTeaserProvider.php +++ /dev/null @@ -1,110 +0,0 @@ -searchManager = $searchManager; - $this->translator = $translator; - $this->articleDocumentClass = $articleDocumentClass; - } - - public function getConfiguration() - { - return new TeaserConfiguration( - $this->translator->trans('sulu_article.article', [], 'admin'), - 'articles', - 'table', - ['title'], - $this->translator->trans('sulu_article.single_selection_overlay_title', [], 'admin') - ); - } - - public function find(array $ids, $locale) - { - if (0 === \count($ids)) { - return []; - } - - $articleIds = $this->getViewDocumentIds($ids, $locale); - - $repository = $this->searchManager->getRepository($this->articleDocumentClass); - $search = $repository->createSearch(); - $search->addQuery(new IdsQuery($articleIds)); - $search->setSize(\count($articleIds)); - - $result = []; - foreach ($repository->findDocuments($search) as $item) { - $excerpt = $item->getExcerpt(); - $result[] = new Teaser( - $item->getUuid(), - 'articles', - $item->getLocale(), - '' !== $excerpt->title ? $excerpt->title : $item->getTitle(), - '' !== $excerpt->description ? $excerpt->description : $item->getTeaserDescription(), - $excerpt->more, - $item->getRoutePath(), - \count($excerpt->images) ? $excerpt->images[0]->id : $item->getTeaserMediaId(), - $this->getAttributes($item) - ); - } - - $idPositions = \array_flip($ids); - \usort($result, function(Teaser $a, Teaser $b) use ($idPositions) { - return $idPositions[$a->getId()] - $idPositions[$b->getId()]; - }); - - return $result; - } - - /** - * Returns attributes for teaser. - */ - protected function getAttributes(ArticleViewDocument $viewDocument): array - { - return [ - 'structureType' => $viewDocument->getStructureType(), - 'type' => $viewDocument->getType(), - ]; - } -} diff --git a/Tests/Application/.env b/Tests/Application/.env index 25b858f47..c767aeb3c 100644 --- a/Tests/Application/.env +++ b/Tests/Application/.env @@ -1,5 +1,2 @@ APP_ENV=test -DATABASE_URL=mysql://root:@127.0.0.1:3306/sulu_test?serverVersion=5.7 -DATABASE_CHARSET=utf8mb4 -DATABASE_COLLATE=utf8mb4_unicode_ci -ELASTICSEARCH_HOST=127.0.0.1:9200 +DATABASE_URL=mysql://root:@127.0.0.1:3306/sulu_test?serverVersion=5.7&charset=utf8mb4&collation=utf8mb4_unicode_ci diff --git a/Tests/Application/Kernel.php b/Tests/Application/Kernel.php index 50cb30bcf..c06f0436a 100644 --- a/Tests/Application/Kernel.php +++ b/Tests/Application/Kernel.php @@ -46,20 +46,8 @@ public function registerBundles(): iterable { $bundles = parent::registerBundles(); $bundles[] = new SuluArticleBundle(); - - if ('phpcr_storage' === $this->config) { - $bundles[] = new ONGRElasticsearchBundle(); - $bundles[] = new SuluHeadlessBundle(); - } - - if ('experimental_storage' === $this->config) { - $bundles[] = new SuluContentBundle(); - $bundles[] = new SuluMessengerBundle(); - } - - if ('extend' === \getenv('ARTICLE_TEST_CASE')) { - $bundles[] = new TestExtendBundle(); - } + $bundles[] = new SuluContentBundle(); + $bundles[] = new SuluMessengerBundle(); return $bundles; } @@ -68,33 +56,8 @@ public function registerContainerConfiguration(LoaderInterface $loader): void { parent::registerContainerConfiguration($loader); - if ('jackrabbit' === \getenv('PHPCR_TRANSPORT')) { - $loader->load(__DIR__ . '/config/versioning.yml'); - } - $loader->load(__DIR__ . '/config/config.yml'); $loader->load(__DIR__ . '/config/config_' . $this->config . '.yml'); - - if ('phpcr_storage' === $this->config) { - $type = 'default'; - if (\getenv('ARTICLE_TEST_CASE')) { - $type = \getenv('ARTICLE_TEST_CASE'); - } - - $loader->load(__DIR__ . '/config/config_' . $type . '.yml'); - } - } - - public function process(ContainerBuilder $container) - { - if ('phpcr_storage' === $this->config) { - // Make some services which were inlined in optimization - $container->getDefinition('sulu_article.content.page_tree_data_provider') - ->setPublic(true); - - $container->getDefinition('sulu_article.elastic_search.article_indexer') - ->setPublic(true); - } } /** @@ -104,9 +67,6 @@ protected function getKernelParameters(): array { $parameters = parent::getKernelParameters(); - $gedmoReflection = new \ReflectionClass(\Gedmo\Exception::class); - $parameters['gedmo_directory'] = \dirname($gedmoReflection->getFileName()); - return $parameters; } diff --git a/Tests/Application/config/config.yml b/Tests/Application/config/config.yml index cd3e3c3bc..2baa18167 100644 --- a/Tests/Application/config/config.yml +++ b/Tests/Application/config/config.yml @@ -1,10 +1,14 @@ -# Doctrine Configuration -doctrine: - orm: - mappings: - gedmo_tree: - type: xml - prefix: Gedmo\Tree\Entity - dir: "%gedmo_directory%/Tree/Entity" - alias: GedmoTree - is_bundle: false +sulu_article: {} + +sulu_core: + content: + structure: + default_type: + article: 'article' + +framework: + # symfony recipe default configuration: + workflows: null + messenger: + transports: + routing: diff --git a/Tests/Application/config/config_default.yml b/Tests/Application/config/config_default.yml deleted file mode 100644 index 9ab6758ad..000000000 --- a/Tests/Application/config/config_default.yml +++ /dev/null @@ -1,12 +0,0 @@ -# This file will not be included when run under extend -sulu_route: - mappings: - Sulu\Bundle\ArticleBundle\Document\ArticleDocument: - generator: "schema" - options: - route_schema: "/articles/{object.getTitle()}" - Sulu\Bundle\ArticleBundle\Document\ArticlePageDocument: - generator: "article_page" - options: - route_schema: "/{translator.trans(\"page\")}-{object.getPageNumber()}" - parent: "{object.getParent().getRoutePath()}" diff --git a/Tests/Application/config/config_experimental_storage.yml b/Tests/Application/config/config_experimental_storage.yml deleted file mode 100644 index e98efc0a6..000000000 --- a/Tests/Application/config/config_experimental_storage.yml +++ /dev/null @@ -1,2 +0,0 @@ -sulu_article: - storage: 'experimental' diff --git a/Tests/Application/config/config_extend.yml b/Tests/Application/config/config_extend.yml deleted file mode 100644 index 9bdd6cfba..000000000 --- a/Tests/Application/config/config_extend.yml +++ /dev/null @@ -1,37 +0,0 @@ -# This file will configure using the TestExtendBundle documents -sulu_document_manager: - mapping: - article: - class: Sulu\Bundle\ArticleBundle\Tests\TestExtendBundle\Document\ArticleDocument - phpcr_type: 'sulu:article' - article_page: - class: Sulu\Bundle\ArticleBundle\Tests\TestExtendBundle\Document\ArticlePageDocument - phpcr_type: 'sulu:articlepage' - -sulu_route: - mappings: - Sulu\Bundle\ArticleBundle\Tests\TestExtendBundle\Document\ArticleDocument: - resource_key: 'article' - generator: "schema" - options: - route_schema: "/articles/{object.getTitle()}" - Sulu\Bundle\ArticleBundle\Tests\TestExtendBundle\Document\ArticlePageDocument: - resource_key: 'article' - generator: "article_page" - options: - route_schema: "/{translator.trans(\"page\")}-{object.getPageNumber()}" - parent: "{object.getParent().getRoutePath()}" - -ongr_elasticsearch: - managers: - default: - mappings: - - TestExtendBundle - live: - mappings: - - TestExtendBundle - -sulu_article: - documents: - article: - view: Sulu\Bundle\ArticleBundle\Tests\TestExtendBundle\Document\ArticleViewDocument diff --git a/Tests/Application/config/config_phpcr_storage.yml b/Tests/Application/config/config_phpcr_storage.yml deleted file mode 100644 index a14c91bf9..000000000 --- a/Tests/Application/config/config_phpcr_storage.yml +++ /dev/null @@ -1,26 +0,0 @@ -sulu_route: - mappings: - Sulu\Bundle\ArticleBundle\Document\ArticleDocument: - generator: "schema" - options: - route_schema: "/articles/{object.getTitle()}" - Sulu\Bundle\ArticleBundle\Document\ArticlePageDocument: - generator: "article_page" - options: - route_schema: "/{translator.trans(\"page\")}-{object.getPageNumber()}" - parent: "{object.getParent().getRoutePath()}" - -sulu_article: - storage: 'phpcr' - index_name: "su_articles_tests" - hosts: ["%env(ELASTICSEARCH_HOST)%"] - default_main_webspace: 'sulu_io' - -ongr_elasticsearch: - analysis: - tokenizer: - pathTokenizer: - type: path_hierarchy - analyzer: - pathAnalyzer: - tokenizer: pathTokenizer diff --git a/Tests/Application/config/routing.yml b/Tests/Application/config/routing.yml index c5199be95..f5cf8bf1b 100644 --- a/Tests/Application/config/routing.yml +++ b/Tests/Application/config/routing.yml @@ -1,4 +1,3 @@ sulu_article_api: - type: rest - resource: "@SuluArticleBundle/Resources/config/routing_api.yml" - prefix: /api + resource: "@SuluArticleBundle/config/routing_admin_api.yaml" + prefix: /admin/api diff --git a/Tests/Application/config/templates/articles/block.xml b/Tests/Application/config/templates/articles/block.xml deleted file mode 100644 index 946006f83..000000000 --- a/Tests/Application/config/templates/articles/block.xml +++ /dev/null @@ -1,35 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default.xml b/Tests/Application/config/templates/articles/default.xml deleted file mode 100644 index ea0f00d94..000000000 --- a/Tests/Application/config/templates/articles/default.xml +++ /dev/null @@ -1,18 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default_blocks_in_blocks.xml b/Tests/Application/config/templates/articles/default_blocks_in_blocks.xml deleted file mode 100644 index 14ecb6942..000000000 --- a/Tests/Application/config/templates/articles/default_blocks_in_blocks.xml +++ /dev/null @@ -1,64 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default_fallback.xml b/Tests/Application/config/templates/articles/default_fallback.xml deleted file mode 100644 index a79fa7179..000000000 --- a/Tests/Application/config/templates/articles/default_fallback.xml +++ /dev/null @@ -1,23 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default_image.xml b/Tests/Application/config/templates/articles/default_image.xml deleted file mode 100644 index 7f9d8d2ce..000000000 --- a/Tests/Application/config/templates/articles/default_image.xml +++ /dev/null @@ -1,19 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default_pages.xml b/Tests/Application/config/templates/articles/default_pages.xml deleted file mode 100644 index 0ed422fdd..000000000 --- a/Tests/Application/config/templates/articles/default_pages.xml +++ /dev/null @@ -1,25 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default_with_page_tree_route.xml b/Tests/Application/config/templates/articles/default_with_page_tree_route.xml deleted file mode 100644 index 7a8ccc510..000000000 --- a/Tests/Application/config/templates/articles/default_with_page_tree_route.xml +++ /dev/null @@ -1,23 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default_with_route.xml b/Tests/Application/config/templates/articles/default_with_route.xml deleted file mode 100644 index d6828c34a..000000000 --- a/Tests/Application/config/templates/articles/default_with_route.xml +++ /dev/null @@ -1,23 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/default_with_search_tags.xml b/Tests/Application/config/templates/articles/default_with_search_tags.xml deleted file mode 100644 index eac7c8a83..000000000 --- a/Tests/Application/config/templates/articles/default_with_search_tags.xml +++ /dev/null @@ -1,45 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/page_tree_route.xml b/Tests/Application/config/templates/articles/page_tree_route.xml deleted file mode 100644 index e45610226..000000000 --- a/Tests/Application/config/templates/articles/page_tree_route.xml +++ /dev/null @@ -1,16 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/page_tree_route_second.xml b/Tests/Application/config/templates/articles/page_tree_route_second.xml deleted file mode 100644 index 25e00bff3..000000000 --- a/Tests/Application/config/templates/articles/page_tree_route_second.xml +++ /dev/null @@ -1,16 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/simple.xml b/Tests/Application/config/templates/articles/simple.xml deleted file mode 100644 index 9583fc808..000000000 --- a/Tests/Application/config/templates/articles/simple.xml +++ /dev/null @@ -1,18 +0,0 @@ - - diff --git a/Tests/Application/config/templates/articles/simple_with_route.xml b/Tests/Application/config/templates/articles/simple_with_route.xml deleted file mode 100644 index 7b8abc30e..000000000 --- a/Tests/Application/config/templates/articles/simple_with_route.xml +++ /dev/null @@ -1,19 +0,0 @@ - - diff --git a/Tests/Application/config/versioning.yml b/Tests/Application/config/versioning.yml deleted file mode 100644 index 61120983a..000000000 --- a/Tests/Application/config/versioning.yml +++ /dev/null @@ -1,3 +0,0 @@ -sulu_document_manager: - versioning: - enabled: true diff --git a/Tests/Application/config/webspaces/sulu.io.blog.xml b/Tests/Application/config/webspaces/sulu.io.blog.xml deleted file mode 100644 index 843bfbc7e..000000000 --- a/Tests/Application/config/webspaces/sulu.io.blog.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - Sulu Blog CMF - sulu_io_blog - - - - - - - default - - - overview - overview - - - - - - - Mainnavigation - - - - - - - - Sulu CMF AT - sulucmf_at - - - - - sulu_io.localhost/blog - - - - - sulu_io.localhost/blog - - - - - sulu_io.localhost/blog - - - - - - diff --git a/Tests/Application/config/webspaces/sulu.io.xml b/Tests/Application/config/webspaces/sulu.io.xml index 21b61c439..51fa1ac67 100644 --- a/Tests/Application/config/webspaces/sulu.io.xml +++ b/Tests/Application/config/webspaces/sulu.io.xml @@ -1,24 +1,31 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://schemas.sulu.io/webspace/webspace http://schemas.sulu.io/webspace/webspace-1.1.xsd"> Sulu CMF - sulu_io + sulu-io + + + Website + - default - overview - overview + default + default + + + + @@ -37,17 +44,20 @@ - sulu_io.localhost + {host} + {host}/en - sulu_io.localhost + {host} + {host}/en - sulu_io.localhost + {host} + {host}/en diff --git a/Tests/Application/config/webspaces/test.xml b/Tests/Application/config/webspaces/test.xml deleted file mode 100644 index dc1f01e8e..000000000 --- a/Tests/Application/config/webspaces/test.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - Test - test - - - - - - - default - - - overview - overview - - - - - - - Mainnavigation - - - - - - - - Test - test - - - - - test.localhost - - - - - test.localhost - - - - - test.localhost - - - - - - diff --git a/Tests/Application/config/webspaces/test2.xml b/Tests/Application/config/webspaces/test2.xml deleted file mode 100644 index 89a70d28f..000000000 --- a/Tests/Application/config/webspaces/test2.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - Test2 - test-2 - - - - - - - default - - - overview - overview - - - - - - - Mainnavigation - - - - - - - - Test2 - test-2 - - - - - test-2.localhost - - - - - test-2.localhost - - - - - test-2.localhost - - - - - - diff --git a/Tests/Functional/.gitignore b/Tests/Functional/.gitignore new file mode 100644 index 000000000..e69de29bb diff --git a/Tests/Functional/Content/ArticleDataProviderTest.php b/Tests/Functional/Content/ArticleDataProviderTest.php deleted file mode 100644 index c25a5c6ac..000000000 --- a/Tests/Functional/Content/ArticleDataProviderTest.php +++ /dev/null @@ -1,635 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - $manager->dropAndCreateIndex(); - $manager = $this->getContainer()->get('es.manager.live'); - $manager->dropAndCreateIndex(); - } - - public function testResolveDataItems() - { - $item = $this->createArticle(); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io']); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(1, $result->getItems()); - $this->assertEquals($item['id'], $result->getItems()[0]->getId()); - } - - public function testResolveDataItemsTypeParam() - { - $item1 = $this->createArticle(); - $item2 = $this->createArticle('Test', 'simple'); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // get all articles with type video - $result = $dataProvider->resolveDataItems( - [], - ['types' => new PropertyParameter('types', 'video')], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(1, $result->getItems()); - $this->assertEquals($item2['id'], $result->getItems()[0]->getId()); - } - - public function testResolveDataItemsTypeParamMultiple() - { - $item1 = $this->createArticle(); - $item2 = $this->createArticle('Test', 'simple'); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // get all articles with type video or blog - $result = $dataProvider->resolveDataItems( - [], - ['types' => new PropertyParameter('types', 'video,blog')], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(2, $result->getItems()); - $this->assertContains( - $item1['id'], - [$result->getItems()[0]->getId(), $result->getItems()[1]->getId()] - ); - $this->assertContains( - $item2['id'], - [$result->getItems()[0]->getId(), $result->getItems()[1]->getId()] - ); - } - - public function testResolveDataItemsTypeParamWrong() - { - $item1 = $this->createArticle(); - $item2 = $this->createArticle('Test', 'simple'); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // get all articles with type other - $result = $dataProvider->resolveDataItems( - [], - ['types' => new PropertyParameter('types', 'other')], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(0, $result->getItems()); - } - - public function testResolveDataItemsStructureTypeParam() - { - $item1 = $this->createArticle(); - $item2 = $this->createArticle('Test', 'simple'); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // get all articles with structureType simple - $result = $dataProvider->resolveDataItems( - [], - ['structureTypes' => new PropertyParameter('structureTypes', 'simple')], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(1, $result->getItems()); - $this->assertEquals($item2['id'], $result->getItems()[0]->getId()); - } - - public function testResolveDataItemsStructureTypeParamMultiple() - { - $item1 = $this->createArticle('Test #1', 'default'); - $item2 = $this->createArticle('Test #2', 'simple'); - $item3 = $this->createArticle('Test no match', 'default_fallback'); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // get all articles with structureType default or simple - $result = $dataProvider->resolveDataItems( - [], - ['structureTypes' => new PropertyParameter('structureTypes', 'default,simple')], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(2, $result->getItems()); - $this->assertContains( - $item1['id'], - [$result->getItems()[0]->getId(), $result->getItems()[1]->getId()] - ); - $this->assertContains( - $item2['id'], - [$result->getItems()[0]->getId(), $result->getItems()[1]->getId()] - ); - } - - public function testResolveDataItemsStructureTypeParamWrong() - { - $item1 = $this->createArticle(); - $item2 = $this->createArticle('Test', 'simple'); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // get all articles with structureType default_fallback - $result = $dataProvider->resolveDataItems( - [], - ['structureTypes' => new PropertyParameter('structureTypes', 'default_fallback')], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(0, $result->getItems()); - } - - public function testResolveDataItemsStructureTypeFromSmartContentFiltering() - { - $item1 = $this->createArticle(); - $item2 = $this->createArticle('Test', 'simple'); - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // get all articles with structureType default_fallback - $result = $dataProvider->resolveDataItems( - ['types' => ['simple']], - [], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(1, $result->getItems()); - - // get all articles with structureType default_fallback - $result = $dataProvider->resolveDataItems( - ['types' => ['default']], - [], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(1, $result->getItems()); - - // get all articles with structureType default_fallback - $result = $dataProvider->resolveDataItems( - ['types' => ['default', 'simple']], - [], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(2, $result->getItems()); - } - - public function testResolveDataItemsPagination() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], null, 1, 2); - $this->assertCount(2, $result->getItems()); - $this->assertTrue($result->getHasNextPage()); - $result = $dataProvider->resolveDataItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], null, 2, 2); - $this->assertCount(1, $result->getItems()); - $this->assertFalse($result->getHasNextPage()); - } - - public function testResolveResourceItemsPaginationWithPageSizeSmallerThanDefaultLimit() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $reflectionClass = new \ReflectionClass($dataProvider); - $reflectionProperty = $reflectionClass->getProperty('defaultLimit'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($dataProvider, 3); - - $pageSize = 20; // need to be bigger as default limit and should have no effect then - - $result = $dataProvider->resolveResourceItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], null, 1, $pageSize); - $this->assertCount(3, $result->getItems()); - $this->assertTrue($result->getHasNextPage()); - - $result = $dataProvider->resolveResourceItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], null, 2, $pageSize); - $this->assertCount(1, $result->getItems()); - $this->assertFalse($result->getHasNextPage()); - } - - public function testResolveResourceItemsPaginationWithLimit() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveResourceItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], 3, 1, 2); - $this->assertCount(2, $result->getItems()); - $this->assertTrue($result->getHasNextPage()); - - $result = $dataProvider->resolveResourceItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], 3, 2, 2); - $this->assertCount(1, $result->getItems()); - $this->assertFalse($result->getHasNextPage()); - } - - public function testResolveResourceItemsWithSegments() - { - if (!\class_exists(SegmentSelect::class)) { - $this->markTestSkipped('Segments did not exist in Sulu <2.2.'); - } - - $items = [ - $this->createArticle('Test Article 1', 'default', 'test', null, ['test' => 's']), - $this->createArticle('Test Article 2', 'default', 'test', null, ['test' => 'w']), - $this->createArticle('Test Article 3', 'default', 'test'), - ]; - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveResourceItems( - ['segmentKey' => 's'], - [], - ['locale' => 'de', 'webspaceKey' => 'test'] - ); - $items = $result->getItems(); - $this->assertCount(2, $items); - - $titles = [ - $items[0]->getTitle(), - $items[1]->getTitle(), - ]; - - $this->assertContains('Test Article 1', $titles); - $this->assertContains('Test Article 3', $titles); - - $result = $dataProvider->resolveResourceItems( - ['segmentKey' => 'w'], - [], - ['locale' => 'de', 'webspaceKey' => 'test'] - ); - $items = $result->getItems(); - $this->assertCount(2, $items); - - $titles = [ - $items[0]->getTitle(), - $items[1]->getTitle(), - ]; - - $this->assertContains('Test Article 2', $titles); - $this->assertContains('Test Article 3', $titles); - } - - public function testResolveResourceItemsPagination() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveResourceItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], null, 1, 2); - $this->assertCount(2, $result->getItems()); - $this->assertTrue($result->getHasNextPage()); - $result = $dataProvider->resolveResourceItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], null, 2, 2); - $this->assertCount(1, $result->getItems()); - $this->assertFalse($result->getHasNextPage()); - } - - public function testResolveDataItemsPaginationWithLimit() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], 3, 1, 2); - $this->assertCount(2, $result->getItems()); - $this->assertTrue($result->getHasNextPage()); - $result = $dataProvider->resolveDataItems([], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io'], 3, 2, 2); - $this->assertCount(1, $result->getItems()); - $this->assertFalse($result->getHasNextPage()); - } - - public function testResolveDataItemsPaginationWithExcluded() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - /** @var DataProviderInterface $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems(['excluded' => [$items[0]['id']]], [], ['locale' => 'de', 'webspaceKey' => 'sulu_io']); - - $this->assertCount(3, $result->getItems()); - for ($i = 0; $i < 3; ++$i) { - $this->assertEquals($items[$i + 1]['id'], $result->getItems()[$i]->getId()); - } - } - - public function testResolveDataItemsPaginationWithReferenceStore() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - $referenceStore = $this->getContainer()->get('sulu_article.reference_store.article'); - $referenceStore->add($items[0]['id']); - - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems( - [], - ['exclude_duplicates' => new PropertyParameter('exclude_duplicates', true)], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertCount(3, $result->getItems()); - for ($i = 0; $i < 3; ++$i) { - $this->assertEquals($items[$i + 1]['id'], $result->getItems()[$i]->getId()); - } - } - - public function testResolveDataItemsPaginationExludeDuplicatedFalse() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - $referenceStore = $this->getContainer()->get('sulu_article.reference_store.article'); - $referenceStore->add($items[0]['id']); - - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems( - [], - ['exclude_duplicates' => new PropertyParameter('exclude_duplicates', false)], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertCount(4, $result->getItems()); - for ($i = 0; $i < 4; ++$i) { - $this->assertEquals($items[$i]['id'], $result->getItems()[$i]->getId()); - } - } - - public function testResolveDataItemsPaginationExludeDuplicatedNull() - { - $items = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - $referenceStore = $this->getContainer()->get('sulu_article.reference_store.article'); - $referenceStore->add($items[0]['id']); - - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems( - [], - [], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertCount(4, $result->getItems()); - for ($i = 0; $i < 4; ++$i) { - $this->assertEquals($items[$i]['id'], $result->getItems()[$i]->getId()); - } - } - - public function testResolveDataItemsWithCustomWebspaceSettings() - { - $items = [ - $this->createArticle('Test-Article 1', 'default', 'test'), - $this->createArticle('Test-Article 2', 'default', 'test-2', ['sulu_io']), - $this->createArticle('Test-Article 2', 'default', 'sulu_io'), - $this->createArticle(), - ]; - - $referenceStore = $this->getContainer()->get('sulu_article.reference_store.article'); - $referenceStore->add($items[0]['id']); - - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems( - [], - [], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertCount(3, $result->getItems()); - } - - public function testResolveResourceItemsWithIgnoreWebspaces() - { - $this->createArticle('Test-Article 1', 'default', 'test', []); - $this->createArticle('Test-Article 2', 'default', 'test-2', ['sulu_io']); - $this->createArticle('Test-Article 2', 'default', 'sulu_io', []); - $this->createArticle(); - - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - // push fake request with `sulu_io` - $this->pushFakeRequest('sulu_io'); - - $result = $dataProvider->resolveResourceItems( - [], - ['ignoreWebspaces' => new PropertyParameter('ignoreWebspaces', true)], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $items = $result->getItems(); - $this->assertCount(4, $items); - $this->assertEquals('test', $items[0]->getTargetWebspace()); - $this->assertEquals('sulu_io', $items[1]->getTargetWebspace()); - $this->assertEquals('sulu_io', $items[2]->getTargetWebspace()); - $this->assertEquals('sulu_io', $items[3]->getTargetWebspace()); - - $this->popFakeRequest(); - - // push fake request with `test` - $this->pushFakeRequest('test'); - - $result = $dataProvider->resolveResourceItems( - [], - ['ignoreWebspaces' => new PropertyParameter('ignoreWebspaces', true)], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $items = $result->getItems(); - $this->assertCount(4, $items); - $this->assertEquals('test', $items[0]->getTargetWebspace()); - $this->assertEquals('test-2', $items[1]->getTargetWebspace()); - $this->assertEquals('sulu_io', $items[2]->getTargetWebspace()); - $this->assertEquals('sulu_io', $items[3]->getTargetWebspace()); - - $this->popFakeRequest(); - } - - private function pushFakeRequest($webspaceKey) - { - $webspaceManager = $this->getContainer()->get('sulu_core.webspace.webspace_manager'); - $webspace = $webspaceManager->findWebspaceByKey($webspaceKey); - - $fakeRequest = Request::create('/', 'GET'); - $fakeRequest->setLocale('de'); - $fakeRequest->attributes->set('_sulu', new RequestAttributes( - [ - 'webspace' => $webspace, - ] - )); - - /** @var RequestStack $requestStack */ - $requestStack = $this->getContainer()->get('request_stack'); - $requestStack->push($fakeRequest); - } - - private function popFakeRequest() - { - /** @var RequestStack $requestStack */ - $requestStack = $this->getContainer()->get('request_stack'); - $requestStack->pop(); - } - - public function testResolveDataItemsWithIgnoreWebspaces() - { - $items = [ - $this->createArticle('Test-Article 1', 'default', 'test'), - $this->createArticle('Test-Article 2', 'default', 'test-2', ['sulu_io']), - $this->createArticle('Test-Article 2', 'default', 'sulu_io'), - $this->createArticle(), - ]; - - $referenceStore = $this->getContainer()->get('sulu_article.reference_store.article'); - $referenceStore->add($items[0]['id']); - - $dataProvider = $this->getContainer()->get('sulu_article.content.data_provider'); - - $result = $dataProvider->resolveDataItems( - [], - ['ignoreWebspaces' => new PropertyParameter('ignoreWebspaces', true)], - ['locale' => 'de', 'webspaceKey' => 'sulu_io'] - ); - - $this->assertCount(4, $result->getItems()); - } - - private function createArticle( - $title = 'Test-Article', - $template = 'default', - $mainWebspace = null, - $additionalWebspaces = null, - $segments = null - ) { - $data = [ - 'title' => $title, - 'template' => $template, - ]; - - if ($mainWebspace) { - $data['mainWebspace'] = $mainWebspace; - } - - if ($additionalWebspaces) { - $data['additionalWebspaces'] = $additionalWebspaces; - } - - if ($segments) { - $data['ext'] = ['excerpt' => ['segments' => $segments]]; - } - - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de&action=publish', - $data - ); - - $response = $this->client->getResponse(); - $this->assertHttpStatusCode(200, $response); - - return \json_decode($response->getContent(), true); - } -} diff --git a/Tests/Functional/Content/PageTreeArticleDataProviderTest.php b/Tests/Functional/Content/PageTreeArticleDataProviderTest.php deleted file mode 100644 index d3129b19d..000000000 --- a/Tests/Functional/Content/PageTreeArticleDataProviderTest.php +++ /dev/null @@ -1,219 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - $manager->dropAndCreateIndex(); - - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.live'); - $manager->dropAndCreateIndex(); - } - - public function testFilterByDataSource() - { - $page1 = $this->createPage('Test Page 1', '/page-1'); - $page2 = $this->createPage('Test Page 2', '/page-1/page-2'); - $page3 = $this->createPage('Test Page 3', '/page-1-1'); - - $articles = [ - $this->createArticle($page1, 'Test 1'), - $this->createArticle($page2, 'Test 2'), - $this->createArticle($page3, 'Test 3'), - ]; - - $dataProvider = $this->getContainer()->get('sulu_article.content.page_tree_data_provider'); - - $result = $dataProvider->resolveDataItems(['dataSource' => $page1->getUuid()], [], ['locale' => 'de']); - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(1, $result->getItems()); - $this->assertEquals($articles[0]['id'], $result->getItems()[0]->getId()); - - $result = $dataProvider->resolveDataItems(['dataSource' => $page1->getUuid(), 'includeSubFolders' => false], [], ['locale' => 'de']); - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(1, $result->getItems()); - $this->assertEquals($articles[0]['id'], $result->getItems()[0]->getId()); - - $result = $dataProvider->resolveDataItems(['dataSource' => $page1->getUuid(), 'includeSubFolders' => true], [], ['locale' => 'de']); - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(2, $result->getItems()); - $this->assertEquals($articles[0]['id'], $result->getItems()[0]->getId()); - $this->assertEquals($articles[1]['id'], $result->getItems()[1]->getId()); - } - - public function testSortByTitle() - { - $page1 = $this->createPage('Test Page', '/page-1'); - - $articles = [ - $this->createArticle($page1, 'Test A'), - $this->createArticle($page1, 'Test B'), - ]; - - $filters = [ - 'dataSource' => $page1->getUuid(), - 'sortBy' => 'title.raw', - 'sortMethod' => 'asc', - ]; - - /** @var PageTreeArticleDataProvider $dataProvider */ - $dataProvider = $this->getContainer()->get('sulu_article.content.page_tree_data_provider'); - $result = $dataProvider->resolveDataItems($filters, [], ['locale' => 'de']); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertEquals($articles[0]['title'], $result->getItems()[0]->getTitle()); - $this->assertEquals($articles[1]['title'], $result->getItems()[1]->getTitle()); - - $filters['sortMethod'] = 'desc'; - - $result = $dataProvider->resolveDataItems($filters, [], ['locale' => 'de']); - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertEquals($articles[0]['title'], $result->getItems()[1]->getTitle()); - $this->assertEquals($articles[1]['title'], $result->getItems()[0]->getTitle()); - } - - public function testResolveDataSource() - { - $page = $this->createPage('Test Page', '/page'); - - $dataProvider = $this->getContainer()->get('sulu_article.content.page_tree_data_provider'); - $result = $dataProvider->resolveDatasource($page->getUuid(), [], ['locale' => 'de']); - - $this->assertInstanceOf(DatasourceItem::class, $result); - $this->assertEquals($page->getUuid(), $result->getId()); - $this->assertEquals($page->getTitle(), $result->getTitle()); - } - - public function testResolveDataItemsUnpublished() - { - $page = $this->createPage('Test Page', '/page', 'de', false); - - $articles = [ - $this->createArticle($page, 'Test 1'), - $this->createArticle($page, 'Test 2'), - ]; - - $this->ensureKernelShutdown(); - self::bootKernel(['sulu.context' => SuluKernel::CONTEXT_WEBSITE]); - - $dataProvider = $this->getContainer()->get('sulu_article.content.page_tree_data_provider'); - $result = $dataProvider->resolveDataItems(['dataSource' => $page->getUuid()], [], ['locale' => 'de']); - - $this->assertInstanceOf(DataProviderResult::class, $result); - $this->assertCount(2, $result->getItems()); - } - - public function testResolveDataSourceUnpublished() - { - $page = $this->createPage('Test Page', '/page', 'de', false); - - $this->ensureKernelShutdown(); - self::bootKernel(['sulu.context' => SuluKernel::CONTEXT_WEBSITE]); - - $dataProvider = $this->getContainer()->get('sulu_article.content.page_tree_data_provider'); - $result = $dataProvider->resolveDatasource($page->getUuid(), [], ['locale' => 'de']); - - $this->assertNull($result); - } - - public function testResolveDataSourceNull() - { - $dataProvider = $this->getContainer()->get('sulu_article.content.page_tree_data_provider'); - - $this->assertNull($dataProvider->resolveDatasource(null, [], ['locale' => 'de'])); - } - - private function createArticle(PageDocument $page, $title = 'Test-Article', $template = 'page_tree_route') - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de&action=publish', - [ - 'title' => $title, - 'template' => $template, - 'routePath' => [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - ], - 'suffix' => Urlizer::urlize($title), - 'path' => $page->getResourceSegment() . '/' . Urlizer::urlize($title), - ], - ] - ); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - /** - * Create a new page. - * - * @param string $title - * @param string $resourceSegment - * @param string $locale - * @param bool $published - * - * @return PageDocument - */ - private function createPage($title, $resourceSegment, $locale = 'de', $published = true) - { - $documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - $sessionManager = $this->getContainer()->get('sulu.phpcr.session'); - - $page = $documentManager->create('page'); - - $uuidReflection = new \ReflectionProperty(PageDocument::class, 'uuid'); - $uuidReflection->setAccessible(true); - $uuidReflection->setValue($page, Uuid::uuid4()->toString()); - - $page->setTitle($title); - $page->setStructureType('default'); - $page->setParent($documentManager->find($sessionManager->getContentPath('sulu_io'))); - $page->setResourceSegment($resourceSegment); - - $documentManager->persist($page, $locale); - - if ($published) { - $documentManager->publish($page, $locale); - } - - $documentManager->flush(); - - return $page; - } -} diff --git a/Tests/Functional/Controller/ArticleControllerTest.php b/Tests/Functional/Controller/ArticleControllerTest.php deleted file mode 100644 index 388c24184..000000000 --- a/Tests/Functional/Controller/ArticleControllerTest.php +++ /dev/null @@ -1,1860 +0,0 @@ - 'blog', 'simple' => 'video', 'default_fallback' => 'other']; - - /** - * @var KernelBrowser - */ - private $client; - - /** - * @var DocumentManagerInterface - */ - private $documentManager; - - /** - * @var UserManager - */ - private $userManager; - - /** - * @var ContactManager - */ - private $contactManager; - - /** - * @var ObjectRepository - */ - private $activityRespository; - - public function setUp(): void - { - parent::setUp(); - $this->client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - $this->purgeDatabase(); - $this->purgeIndex(); - - $this->documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - - $this->userManager = $this->getContainer()->get('sulu_security.user_manager'); - $this->contactManager = $this->getContainer()->get('sulu_contact.contact_manager'); - - $this->activityRespository = $this->getEntityManager()->getRepository(Activity::class); - - $collectionTypes = new LoadCollectionTypes(); - $collectionTypes->load($this->getEntityManager()); - $mediaTypes = new LoadMediaTypes(); - $mediaTypes->load($this->getEntityManager()); - } - - protected function post( - $title = 'Test-Article', - $template = 'default', - $authored = '2016-01-01', - $action = null - ) { - $requestData = [ - 'title' => $title, - 'template' => $template, - 'authored' => \date('c', \strtotime($authored)), - 'action' => $action, - ]; - - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de', - $requestData - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - protected function postPage($article, $pageTitle = 'Test-Page') - { - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article['id'] . '/pages?locale=de', - [ - 'pageTitle' => $pageTitle, - 'template' => $article['template'], - 'authored' => \date('c', \strtotime('2016-01-01')), - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - public function testPost($title = 'Test-Article', $template = 'default') - { - $response = $this->post($title, $template); - $this->assertEquals($title, $response['title']); - $this->assertEquals($this->getRoute($title), $response['route']); - $this->assertEquals(self::$typeMap[$template], $response['articleType']); - $this->assertEquals($template, $response['template']); - $this->assertEquals('2016-01-01', \date('Y-m-d', \strtotime($response['authored']))); - $this->assertEquals($this->getTestUser()->getContact()->getId(), $response['author']); - $this->assertFalse($response['customizeWebspaceSettings']); - - $this->assertNotNull($this->findViewDocument($response['id'], 'de')); - - /** @var ActivityInterface $activity */ - $activity = $this->activityRespository->findOneBy(['type' => 'created']); - $this->assertNotNull($activity); - - return $response; - } - - public function testPostWithAuthor($title = 'Sulu is awesome', $locale = 'de') - { - $user = $this->createContact(); - - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=' . $locale, - [ - 'title' => $title, - 'template' => 'default', - 'authored' => \date('c', \strtotime('2016-01-01')), - 'author' => $user->getId(), - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals($title, $response['title']); - $this->assertEquals($this->getRoute($title), $response['route']); - $this->assertEquals('2016-01-01', \date('Y-m-d', \strtotime($response['authored']))); - $this->assertEquals($user->getId(), $response['author']); - - $this->assertNotNull($this->findViewDocument($response['id'], 'de')); - } - - protected function get($id, $locale = 'de') - { - $this->client->jsonRequest('GET', '/api/articles/' . $id . '?locale=' . $locale); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - public function testGet() - { - $article = $this->testPost(); - - $response = $this->get($article['id']); - foreach ($article as $name => $value) { - $this->assertEquals($value, $response[$name]); - } - } - - protected function put($title = 'Sulu is awesome', $locale = 'de', $shadowLocale = null, $article = null) - { - if (!$article) { - $article = $this->post(); - } - - $requestData = [ - 'title' => $title, - 'template' => 'default', - 'authored' => \date('c', \strtotime('2016-01-01')), - ]; - - if ($shadowLocale) { - $requestData['shadowOn'] = true; - $requestData['shadowBaseLanguage'] = $shadowLocale; - } - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=' . $locale, - $requestData - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - public function testPut($title = 'Sulu is awesome', $locale = 'de', $article = null) - { - if (!$article) { - $article = $this->testPost(); - } - - $response = $this->put($title, $locale, null, $article); - $this->assertNotEquals($article['title'], $response['title']); - $this->assertEquals($article['route'], $response['route']); - $this->assertEquals($title, $response['title']); - $this->assertEquals('2016-01-01', \date('Y-m-d', \strtotime($response['authored']))); - $this->assertEquals($this->getTestUser()->getContact()->getId(), $response['author']); - - $this->assertNotNull($this->findViewDocument($response['id'], 'de')); - - /** @var ActivityInterface $activity */ - $activity = $this->activityRespository->findOneBy(['type' => 'modified']); - $this->assertSame((string) $article['id'], $activity->getResourceId()); - - return $article; - } - - public function testPutWithAuthor($title = 'Sulu is awesome', $locale = 'de') - { - $user = $this->createContact(); - - $article = $this->testPost(); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=' . $locale, - [ - 'title' => $title, - 'template' => 'default', - 'authored' => \date('c', \strtotime('2016-01-01')), - 'author' => $user->getId(), - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals($title, $response['title']); - $this->assertEquals($article['route'], $response['route']); - $this->assertEquals('2016-01-01', \date('Y-m-d', \strtotime($response['authored']))); - $this->assertEquals($user->getId(), $response['author']); - - $this->assertNotNull($this->findViewDocument($response['id'], 'de')); - } - - public function testPutTranslation($title = 'Sulu is nice') - { - $article = $this->put('Sulu ist toll', 'de'); - $response = $this->put($title, 'en', null, $article); - - $this->assertNotEquals($article['title'], $response['title']); - $this->assertEquals($this->getRoute($title), $response['route']); - $this->assertEquals($title, $response['title']); - $this->assertEquals('2016-01-01', \date('Y-m-d', \strtotime($response['authored']))); - $this->assertEquals($this->getTestUser()->getContact()->getId(), $response['author']); - - $this->assertNotNull($this->findViewDocument($response['id'], 'de')); - - /** @var ActivityInterface $activity */ - $activity = $this->activityRespository->findOneBy(['type' => 'translation_added']); - $this->assertSame((string) $article['id'], $activity->getResourceId()); - } - - public function provideCustomWebspaceSettings() - { - return [ - [ - 'Sulu is nice', - 'de', - ], - [ - 'Sulu is nice', - 'de', - 'test', - ['sulu_io', 'test-2'], - ], - [ - 'Sulu is nice', - 'de', - 'sulu_io', - ['test-2'], - ], - [ - 'Sulu is nice', - 'de', - 'sulu_io', - ], - ]; - } - - /** - * @dataProvider provideCustomWebspaceSettings - */ - public function testPutCustomWebspaceSettings($title, $locale, $mainWebspace = null, $additionalWebspaces = null) - { - $article = $this->testPost(); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=' . $locale, - [ - 'title' => $title, - 'template' => 'default', - 'mainWebspace' => $mainWebspace, - 'additionalWebspaces' => $additionalWebspaces, - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - // check response - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals($title, $response['title']); - $customizeWebspaceSettings = $response['customizeWebspaceSettings']; - $this->assertEquals(null !== $mainWebspace, $customizeWebspaceSettings); - $this->assertEquals($mainWebspace ?? 'sulu_io', $response['mainWebspace']); - $this->assertEquals($customizeWebspaceSettings ? $additionalWebspaces : ($additionalWebspaces ?? []), $response['additionalWebspaces']); - - // check if phpcr document is correct - $this->documentManager->clear(); - - /** @var ArticleDocument $document */ - $document = $this->documentManager->find($response['id'], 'de'); - - $this->assertEquals($title, $document->getTitle()); - $this->assertEquals($mainWebspace, $document->getMainWebspace()); - $this->assertEquals($additionalWebspaces, $document->getAdditionalWebspaces()); - - /** @var ArticleViewDocument $viewDocument */ - $viewDocument = $this->findViewDocument($response['id'], 'de'); - $this->assertNotNull($viewDocument); - $this->assertEquals($mainWebspace ?? 'sulu_io', $viewDocument->getMainWebspace()); - $this->assertEquals($additionalWebspaces ?? [], $viewDocument->getAdditionalWebspaces()); - - // test that ghost do not serve default webspace settings - $response = $this->get($article['id'], 'en'); - $this->assertEquals('sulu_io', $response['mainWebspace']); - $this->assertEquals([], $response['additionalWebspaces']); - - $viewDocument = $this->findViewDocument($response['id'], 'en'); - $this->assertNotNull($viewDocument); - $this->assertEquals('sulu_io', $viewDocument->getMainWebspace()); - $this->assertEquals([], $viewDocument->getAdditionalWebspaces()); - } - - /** - * @dataProvider provideCustomWebspaceSettings - */ - public function testPutCustomWebspaceSettingsWithShadow($title, $locale, $mainWebspace = null, $additionalWebspaces = null) - { - $article = $this->testPost(); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=' . $locale, - [ - 'title' => $title, - 'template' => 'default', - 'mainWebspace' => $mainWebspace, - 'additionalWebspaces' => $additionalWebspaces, - ] - ); - - $this->put('Sulu is great', 'en', $locale, $article); - - $response = $this->get($article['id'], 'en'); - $this->assertEquals($title, $response['title']); - $customizeWebspaceSettings = $response['customizeWebspaceSettings']; - $this->assertEquals(null !== $mainWebspace, $customizeWebspaceSettings); - $this->assertEquals($mainWebspace ?? 'sulu_io', $response['mainWebspace']); - $this->assertEquals($customizeWebspaceSettings ? $additionalWebspaces : ($additionalWebspaces ?? []), $response['additionalWebspaces']); - - /** @var ArticleViewDocument $viewDocument */ - $viewDocument = $this->findViewDocument($response['id'], 'en'); - $this->assertNotNull($viewDocument); - $this->assertEquals($mainWebspace ?? 'sulu_io', $viewDocument->getMainWebspace()); - $this->assertEquals($additionalWebspaces ?? [], $viewDocument->getAdditionalWebspaces()); - } - - public function testGetEmptyDocument() - { - $title = 'Sulu ist toll'; - $article = $this->testPut($title, 'de'); - - $this->client->jsonRequest('GET', '/api/articles/' . $article['id'] . '?locale=en'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals('', $response['title']); - $this->assertEquals(null, $response['authored']); - $this->assertEquals(null, $response['author']); - $this->assertEquals($article['template'], $response['template']); - } - - public function testGetShadow() - { - $title = 'Sulu ist toll'; - $article = $this->put($title, 'de'); - - $this->put('Sulu is great', 'en', 'de', $article); - - $this->client->jsonRequest('GET', '/api/articles/' . $article['id'] . '?locale=en'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals($title, $response['title']); - $this->assertEquals('2016-01-01', \date('Y-m-d', \strtotime($response['authored']))); - $this->assertEquals($this->getTestUser()->getContact()->getId(), $response['author']); - $this->assertEquals(['name' => 'shadow', 'value' => 'de'], $response['type']); - $this->assertEquals('/articles/sulu-is-great', $response['route']); - $this->assertTrue($response['shadowOn']); - $this->assertEquals('de', $response['shadowBaseLanguage']); - } - - public function testCGetGhost() - { - $title1 = 'Sulu ist toll - Test 1'; - $article1 = $this->put($title1, 'de'); - - $title2 = 'Sulu ist toll - Test 2'; - $article2 = $this->put($title2, 'de'); - - $title2_EN = $title2 . ' (EN)'; - $this->put($title2_EN, 'en', null, $article2); - - // Retrieve articles in 'de'. - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $title1], $items); - $this->assertContains([$article2['id'], $title2], $items); - - // Retrieve articles in 'en'. - $this->client->jsonRequest('GET', '/api/articles?locale=en&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $title1], $items); - $this->assertContains([$article2['id'], $title2_EN], $items); - } - - public function testCGetExcludeGhost() - { - $title1 = 'Sulu ist toll - Test 1'; - $this->put($title1, 'de'); - - $title2 = 'Sulu ist toll - Test 2'; - $article2 = $this->put($title2, 'de'); - - $title2_EN = $title2 . ' (EN)'; - $this->put($title2_EN, 'en', null, $article2); - - // Retrieve articles in 'de'. - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog&fields=title&exclude-ghosts=true'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - // Retrieve articles in 'en'. - $this->client->jsonRequest('GET', '/api/articles?locale=en&types=blog&fields=title&exclude-ghosts=true'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - } - - public function testCGetShadow() - { - $title1 = 'Sulu ist toll - Test 1'; - $article1 = $this->put($title1, 'de'); - - $title2 = 'Sulu ist toll - Test 2'; - $article2 = $this->put($title2, 'de'); - - // create second language for article2 - $title2_EN = $title2 . ' (EN)'; - $this->put($title2_EN, 'en', null, $article2); - - $title3 = 'Sulu ist toll - Test 3'; - $article3 = $this->put($title3, 'de'); - - // create shadow for article3 - $title3_EN = $title2 . ' (EN)'; - $this->put($title3_EN, 'en', 'de', $article3); - - // Retrieve articles in 'de'. - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(3, $response['total']); - $this->assertCount(3, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $title1], $items); - $this->assertContains([$article2['id'], $title2], $items); - $this->assertContains([$article3['id'], $title3], $items); - - // Retrieve articles in 'en'. - $this->client->jsonRequest('GET', '/api/articles?locale=en&types=blog&fields=title,route'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(3, $response['total']); - $this->assertCount(3, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title'], $item['localizationState']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $title1, ['state' => 'ghost', 'locale' => 'de']], $items); - $this->assertContains([$article2['id'], $title2_EN, ['state' => 'localized']], $items); - $this->assertContains([$article3['id'], $title3, ['state' => 'shadow', 'locale' => 'de']], $items); - } - - public function testCGetExcludeShadow() - { - $title1 = 'Sulu ist toll - Test 1'; - $article1 = $this->put($title1, 'de'); - - $title2 = 'Sulu ist toll - Test 2'; - $article2 = $this->put($title2, 'de'); - - // create second language for article2 - $title2_EN = $title2 . ' (EN)'; - $this->put($title2_EN, 'en', null, $article2); - - $title3 = 'Sulu ist toll - Test 3'; - $article3 = $this->put($title3, 'de'); - - // create shadow for article3 - $title3_EN = $title2 . ' (EN)'; - $this->put($title3_EN, 'en', 'de', $article3); - - // Retrieve articles in 'de'. - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog&fields=title&exclude-shadows=true'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(3, $response['total']); - $this->assertCount(3, $response['_embedded']['articles']); - - // Retrieve articles in 'en'. - $this->client->jsonRequest('GET', '/api/articles?locale=en&types=blog&fields=title,route&exclude-shadows=true'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - } - - public function testPutExtensions( - $title = 'Sulu is awesome', - $extensions = [ - 'seo' => [ - 'title' => 'Seo title', - 'description' => 'Seo description', - 'keywords' => 'Seo keywords', - 'canonicalUrl' => 'http://canonical.lo', - 'hideInSitemap' => true, - 'noFollow' => false, - 'noIndex' => true, - ], - 'excerpt' => [ - 'title' => 'Excerpt title', - 'description' => 'Excerpt title', - 'more' => 'Excerpt more', - 'categories' => [1], - 'tags' => [ - 'Excerpt', - 'Tags', - ], - 'icon' => [ - 'displayOption' => 'top', - 'ids' => [1], - ], - 'images' => [ - 'displayOption' => 'top', - 'ids' => [1], - ], - 'audience_targeting_groups' => [], - 'segments' => [], - ], - ] - ) { - $media = $this->createMedia(); - - $extensions['excerpt']['icon']['ids'] = [$media->getId()]; - $extensions['excerpt']['images']['ids'] = [$media->getId()]; - - $article = $this->testPost(); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=de', - [ - 'title' => $title, - 'template' => 'default', - 'ext' => $extensions, - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertNotEquals($article['title'], $response['title']); - $this->assertEquals($title, $response['title']); - $this->assertEquals($extensions['seo'], $response['ext']['seo']); - - if (!\class_exists(SegmentSelect::class)) { - // segment is only returned for sulu versions >= 2.2 - unset($extensions['excerpt']['segments']); - } - - $this->assertEquals($extensions['excerpt'], $response['ext']['excerpt']); - } - - public function testPutDifferentTemplate($title = 'Sulu', $description = 'Sulu is awesome') - { - $article = $this->testPost(); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=de', - ['title' => $title, 'description' => $description, 'template' => 'simple'] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertNotEquals($article['title'], $response['title']); - $this->assertEquals($title, $response['title']); - $this->assertEquals('simple', $response['template']); - $this->assertEquals(self::$typeMap['simple'], $response['articleType']); - $this->assertEquals($description, $response['description']); - } - - public function testPutDifferentLocale($title = 'Sulu is awesome') - { - $article = $this->testPost(); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=en', - ['title' => $title, 'template' => 'default'] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(['de', 'en'], $response['contentLocales']); - $this->assertEquals($title, $response['title']); - } - - public function testCGet() - { - $article1 = $this->testPost('Sulu'); - $this->flush(); - $article2 = $this->testPost('Sulu is awesome'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title']], $items); - $this->assertContains([$article2['id'], $article2['title']], $items); - } - - public function testCGetIds() - { - $article1 = $this->testPost('Sulu'); - $this->flush(); - $article2 = $this->testPost('Sulu is awesome'); - $this->flush(); - - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&ids=' . \implode(',', [$article2['id'], $article1['id']]) - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $this->assertEquals($article2['id'], $response['_embedded']['articles'][0]['id']); - $this->assertEquals($article1['id'], $response['_embedded']['articles'][1]['id']); - } - - public function testCGetAuthoredRange() - { - $this->post('Sulu'); - $this->flush(); - $article = $this->post('Sulu is awesome', 'default', '2016-01-10'); - $this->flush(); - - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&types=blog&authoredFrom=2016-01-09&authoredTo=2016-01-11&fields=title' - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - - $this->assertEquals($response['_embedded']['articles'][0]['title'], $article['title']); - $this->assertEquals($response['_embedded']['articles'][0]['id'], $article['id']); - } - - public function testCGetWorkflowStage() - { - $this->post('Sulu'); - $this->flush(); - $article = $this->post('Sulu is awesome', 'default', '2016-01-10', 'publish'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog&workflowStage=published&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - - $this->assertEquals($response['_embedded']['articles'][0]['title'], $article['title']); - $this->assertEquals($response['_embedded']['articles'][0]['id'], $article['id']); - } - - public function testCGetSearch() - { - $this->testPost('Sulu'); - $this->flush(); - $article2 = $this->testPost('Sulu is awesome'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&searchFields=title&search=awesome&types=blog&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - $this->assertEquals($article2['id'], $response['_embedded']['articles'][0]['id']); - $this->assertEquals($article2['title'], $response['_embedded']['articles'][0]['title']); - } - - public function testCGetSearchWithoutSearchFields() - { - $this->testPost('Sulu'); - $this->flush(); - $article2 = $this->testPost('Sulu is awesome'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&search=awesome&types=blog&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - $this->assertEquals($article2['id'], $response['_embedded']['articles'][0]['id']); - $this->assertEquals($article2['title'], $response['_embedded']['articles'][0]['title']); - } - - public function testCGetSearchRoutePath() - { - $articles = [ - $this->testPost('Sulu'), - $this->testPost('Sulu is awesome'), - ]; - $this->flush(); - - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&searchFields=route_path&search=/articles&types=blog&fields=title' - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - $this->assertEquals($articles[0]['id'], $response['_embedded']['articles'][0]['id']); - $this->assertEquals($articles[0]['title'], $response['_embedded']['articles'][0]['title']); - $this->assertEquals($articles[1]['id'], $response['_embedded']['articles'][1]['id']); - $this->assertEquals($articles[1]['title'], $response['_embedded']['articles'][1]['title']); - } - - public function testCGetSearchFieldRoutePath() - { - $routePathData = [ - 'suffix' => '/test-route', - ]; - $article = $this->postPageTreeRoute($routePathData, 'Article Name'); - - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&page=1&limit=10&fields=id,title,creatorFullName,changerFullName,authorFullName,routePath&search=test-route&flat=true' - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - $this->assertEquals($article['id'], $response['_embedded']['articles'][0]['id']); - $this->assertEquals($article['title'], $response['_embedded']['articles'][0]['title']); - } - - public function testCGetSearchCaseInsensitive() - { - $this->testPost('Sulu'); - $this->flush(); - $article2 = $this->testPost('Sulu is awesome'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&searchFields=title&search=AwEsoMe&types=blog&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - $this->assertEquals($article2['id'], $response['_embedded']['articles'][0]['id']); - $this->assertEquals($article2['title'], $response['_embedded']['articles'][0]['title']); - } - - public function testCGetSort() - { - $article1 = $this->testPost('Hikaru Sulu'); - $this->flush(); - $article2 = $this->testPost('USS Enterprise'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&sortBy=title&sortOrder=desc&types=blog&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - $this->assertEquals($article2['id'], $response['_embedded']['articles'][0]['id']); - $this->assertEquals($article2['title'], $response['_embedded']['articles'][0]['title']); - $this->assertEquals($article1['id'], $response['_embedded']['articles'][1]['id']); - $this->assertEquals($article1['title'], $response['_embedded']['articles'][1]['title']); - } - - public function testCGetTypes() - { - $article1 = $this->testPost('Sulu'); - $this->flush(); - $article2 = $this->testPost('Sulu is awesome', 'simple'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title']], $items); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=video&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article2['id'], $article2['title']], $items); - } - - public function testCGetMultipleTypes() - { - $article1 = $this->testPost('Sulu', 'default'); - $article2 = $this->testPost('Sulu is awesome', 'simple'); - $article3 = $this->testPost('Sulu is great', 'default_fallback'); - $this->flush(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog,video&fields=title'); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - } - - public function testCGetFilterByContactId() - { - // create contact1 - $contact1 = $this->contactManager->save( - [ - 'firstName' => 'Testi 1', - 'lastName' => 'Testo 1', - ], - null, - false, - true - ); - - // create contact2 - $contact2 = $this->contactManager->save( - [ - 'firstName' => 'Testi 2', - 'lastName' => 'Testo 2', - ], - null, - false, - true - ); - - // create contact3 - $contact3 = $this->contactManager->save( - [ - 'firstName' => 'Testi 3', - 'lastName' => 'Testo 3', - ], - null, - false, - true - ); - - // create user1 - $user1 = $this->userManager->save( - [ - 'username' => 'testi.testo1', - 'email' => 'testi.testo1@LOL.xyz', - 'password' => 'ThisIsSave!#123', - 'contact' => [ - 'id' => $contact1->getId(), - ], - ], - 'de', - null, - false, - true - ); - - // create user2 - $user2 = $this->userManager->save( - [ - 'username' => 'testi.testo2', - 'email' => 'testi.testo2@LOL.xyz', - 'password' => 'ThisIsSave!#123', - 'contact' => [ - 'id' => $contact2->getId(), - ], - ], - 'de', - null, - false, - true - ); - - // create user3 - $user3 = $this->userManager->save( - [ - 'username' => 'testi.testo3', - 'email' => 'testi.testo3@LOL.xyz', - 'password' => 'ThisIsSave!#123', - 'contact' => [ - 'id' => $contact3->getId(), - ], - ], - 'de', - null, - false, - true - ); - - /** @var ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('first title'); - $article->setStructureType('default'); - // user 3 is author - $article->setAuthor($contact3->getId()); - - // user 1 is creator - $this->documentManager->persist($article, 'de', ['user' => $user1->getId()]); - $this->documentManager->publish($article, 'de'); - $this->documentManager->flush(); - - // user 2 is changer - $this->documentManager->persist($article, 'de', ['user' => $user2->getId()]); - $this->documentManager->publish($article, 'de'); - $this->documentManager->flush(); - - // add article - /** @var ArticleDocument $article */ - $article2 = $this->documentManager->create('article'); - $article2->setTitle('first title'); - $article2->setStructureType('default'); - - $this->documentManager->persist($article2, 'de', ['user' => $user1->getId()]); - $this->documentManager->publish($article2, 'de'); - $this->documentManager->flush(); - - // retrieve all articles for user1 - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&searchFields=title&types=blog&contactId=' . $user1->getContact()->getId() - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - // retrieve all articles for user2 - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&searchFields=title&types=blog&contactId=' . $user2->getContact()->getId() - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - - // retrieve all articles for user1 - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&searchFields=title&types=blog&contactId=' . $user1->getContact()->getId() - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - // retrieve all articles for user2 - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&searchFields=title&types=blog&contactId=' . $user2->getContact()->getId() - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - - // retrieve all articles for user3 - $this->client->jsonRequest( - 'GET', - '/api/articles?locale=de&searchFields=title&types=blog&contactId=' . $user3->getContact()->getId() - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(1, $response['total']); - $this->assertCount(1, $response['_embedded']['articles']); - } - - public function testDelete() - { - $article = $this->testPost('Sulu'); - $this->flush(); - - $this->client->jsonRequest('DELETE', '/api/articles/' . $article['id']); - $this->flush(); - - $this->assertHttpStatusCode(204, $this->client->getResponse()); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog'); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(0, $response['total']); - $this->assertCount(0, $response['_embedded']['articles']); - - $this->assertNull($this->findViewDocument($article['id'], 'de')); - - /** @var ActivityInterface $activity */ - $activity = $this->activityRespository->findOneBy(['type' => 'removed']); - $this->assertSame((string) $article['id'], $activity->getResourceId()); - } - - public function testCDelete() - { - $article1 = $this->testPost('Sulu'); - $this->flush(); - $article2 = $this->testPost('Sulu is awesome', 'simple'); - $this->flush(); - - $this->client->jsonRequest('DELETE', '/api/articles?ids=' . \implode(',', [$article1['id'], $article2['id']])); - $this->flush(); - - $this->assertHttpStatusCode(204, $this->client->getResponse()); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&types=blog'); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(0, $response['total']); - $this->assertCount(0, $response['_embedded']['articles']); - - $this->assertNull($this->findViewDocument($article1['id'], 'de')); - $this->assertNull($this->findViewDocument($article2['id'], 'de')); - } - - public function testCopy() - { - // create article - $sourceArticle = $this->testPost('Sulu ist toll - Artikel 1'); - $this->publish($sourceArticle['id']); - $this->flush(); - - // trigger copy action - $this->client->jsonRequest('POST', - \sprintf('/api/articles/%s?action=copy', $sourceArticle['id']) - ); - $response = $this->client->getResponse(); - - $result = \json_decode($response->getContent(), true); - $this->assertHttpStatusCode(200, $response); - - $this->assertNotEquals($sourceArticle['id'], $result['id']); - $this->assertEquals($sourceArticle['title'], $result['title']); - $this->assertEquals($sourceArticle['articleType'], $result['articleType']); - $this->assertEquals(false, $result['publishedState']); - } - - public function testCopyLocaleWithoutSource() - { - // prepare vars - $locale = 'de'; - $destLocale = 'en'; - - // create article in default locale - $article1 = $this->testPost('Sulu ist toll - Artikel 1'); - $this->publish($article1['id']); - $article2 = $this->testPost('Sulu ist toll - Artikel 2'); - $this->publish($article2['id']); - $this->flush(); - - // get all articles in default locale - $this->client->jsonRequest('GET', '/api/articles?locale=' . $locale . '&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title']], $items); - $this->assertContains([$article2['id'], $article2['title']], $items); - - // get all articles in dest locale (both should be ghosts) - $this->client->jsonRequest('GET', '/api/articles?locale=' . $destLocale . '&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title'], $item['localizationState']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title'], ['state' => 'ghost', 'locale' => 'de']], $items); - $this->assertContains([$article2['id'], $article2['title'], ['state' => 'ghost', 'locale' => 'de']], $items); - - // request copy-locale post action for article1 (published de locale should be returned) - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article1['id'] . '?locale=' . $locale . '&dest=' . $destLocale . '&action=copy-locale' - ); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertEquals($article1['id'], $response['id']); - $this->assertEquals(true, $response['publishedState']); - $this->assertEquals([$locale, $destLocale], $response['contentLocales']); - - // get all articles in dest locale (now only one should be a ghost) - $this->client->jsonRequest('GET', '/api/articles?locale=' . $destLocale . '&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title'], $item['localizationState']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title'], ['state' => 'localized']], $items); - $this->assertContains([$article2['id'], $article2['title'], ['state' => 'ghost', 'locale' => 'de']], $items); - } - - public function testCopyLocaleWithSource() - { - // prepare vars - $locale = 'en'; - $srclocale = 'de'; - $destLocale = 'en'; - - // create article in default locale - $article1 = $this->testPost('Sulu ist toll - Artikel 1'); - $this->publish($article1['id']); - $article2 = $this->testPost('Sulu ist toll - Artikel 2'); - $this->publish($article2['id']); - $this->flush(); - - // get all articles in default locale - $this->client->jsonRequest('GET', '/api/articles?locale=' . $srclocale . '&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title']], $items); - $this->assertContains([$article2['id'], $article2['title']], $items); - - // get all articles in dest locale (both should be ghosts) - $this->client->jsonRequest('GET', '/api/articles?locale=' . $destLocale . '&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title'], $item['localizationState']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title'], ['state' => 'ghost', 'locale' => 'de']], $items); - $this->assertContains([$article2['id'], $article2['title'], ['state' => 'ghost', 'locale' => 'de']], $items); - - // request copy-locale post action for article1 (unpublished en locale should be returned) - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article1['id'] . '?locale=' . $locale . '&src=' . $srclocale . '&dest=' . $destLocale . '&action=copy-locale' - ); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertEquals($article1['id'], $response['id']); - $this->assertEquals(false, $response['publishedState']); - $this->assertEquals([$srclocale, $destLocale], $response['contentLocales']); - - // get all articles in dest locale (now only one should be a ghost) - $this->client->jsonRequest('GET', '/api/articles?locale=' . $destLocale . '&types=blog&fields=title'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals(2, $response['total']); - $this->assertCount(2, $response['_embedded']['articles']); - - $items = \array_map( - function($item) { - return [$item['id'], $item['title'], $item['localizationState']]; - }, - $response['_embedded']['articles'] - ); - - $this->assertContains([$article1['id'], $article1['title'], ['state' => 'localized']], $items); - $this->assertContains([$article2['id'], $article2['title'], ['state' => 'ghost', 'locale' => 'de']], $items); - - /** @var ActivityInterface $activity */ - $activity = $this->activityRespository->findOneBy(['type' => 'translation_copied']); - $this->assertSame((string) $article1['id'], $activity->getResourceId()); - } - - public function testCgetFilterByCategory() - { - $title = 'Test-Article'; - $template = 'default'; - $category = $this->createCategory(); - - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de', - [ - 'title' => $title, - 'template' => $template, - 'authored' => \date('c', \strtotime('2016-01-01')), - 'ext' => ['excerpt' => ['categories' => [$category->getId()]]], - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $article1 = \json_decode($this->client->getResponse()->getContent(), true); - // create second article which should not appear in response - $article2 = $this->post(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&categoryId=' . $category->getId()); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $result = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertCount(1, $result['_embedded']['articles']); - $this->assertEquals($article1['id'], $result['_embedded']['articles'][0]['id']); - } - - public function testCgetFilterByTag() - { - $title = 'Test-Article'; - $template = 'default'; - $tag = $this->createTag(); - - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de', - [ - 'title' => $title, - 'template' => $template, - 'authored' => \date('c', \strtotime('2016-01-01')), - 'ext' => ['excerpt' => ['tags' => [$tag->getName()]]], - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $article1 = \json_decode($this->client->getResponse()->getContent(), true); - // create second article which should not appear in response - $article2 = $this->post(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&tagId=' . $tag->getId()); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $result = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertCount(1, $result['_embedded']['articles']); - $this->assertEquals($article1['id'], $result['_embedded']['articles'][0]['id']); - } - - public function testCgetFilterByPage() - { - $page = $this->createPage('Test Page', '/test-page'); - - $routePathData = [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - 'webspace' => 'sulu_io', - ], - 'suffix' => 'test-article', - 'path' => '/test-page/test-article', - ]; - - $article1 = $this->postPageTreeRoute($routePathData); - - // create second article which should not appear in response - $this->post(); - - $this->client->jsonRequest('GET', '/api/articles?locale=de&pageId=' . $page->getUuid()); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $result = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertCount(1, $result['_embedded']['articles']); - $this->assertEquals($article1['id'], $result['_embedded']['articles'][0]['id']); - } - - public function testPostPageTreeRoute() - { - $page = $this->createPage('Test Page', '/test-page'); - - $routePathData = [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - ], - 'suffix' => '/test-article', - 'path' => '/test-page/test-article', - ]; - - $response = $this->postPageTreeRoute($routePathData); - - $this->assertEquals('Test Article', $response['title']); - $this->assertEquals('/test-page/test-article', $response['route']); - $this->assertEquals($routePathData, $response['routePath']); - } - - public function testPostPageTreeRouteGenerate() - { - $page = $this->createPage('Test Page', '/test-page'); - - $routePathData = [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - ], - 'suffix' => '/articles/test-article', - 'path' => '/test-page/articles/test-article', - ]; - - $response = $this->postPageTreeRoute(['page' => $routePathData['page']]); - - $this->assertEquals('Test Article', $response['title']); - $this->assertEquals('/test-page/articles/test-article', $response['route']); - $this->assertEquals($routePathData, $response['routePath']); - } - - public function testPostPageTreeRouteGeneratePublishPage() - { - $page = $this->createPage('Test Page', '/test-page'); - - $routePathData = [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - ], - 'suffix' => 'articles/test-article', - 'path' => '/test-page/articles/test-article', - ]; - - $article = $this->postPageTreeRoute(['page' => $routePathData['page']]); - - $page->setResourceSegment('/test-page-2'); - - $this->documentManager->persist($page, 'de'); - $this->documentManager->publish($page, 'de'); - $this->documentManager->flush(); - $this->documentManager->clear(); - - $this->client->jsonRequest('GET', '/api/articles/' . $article['id'] . '?locale=de'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals('Test Article', $response['title']); - $this->assertEquals('/test-page-2/articles/test-article', $response['route']); - $this->assertEquals( - [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - ], - 'suffix' => '/articles/test-article', - 'path' => '/test-page-2/articles/test-article', - ], - $response['routePath'] - ); - } - - public function testPostPageTreeRouteGenerateMovePage() - { - $page1 = $this->createPage('Page 1', '/page-1'); - $page2 = $this->createPage('Page 2', '/page-2'); - - $routePathData = [ - 'page' => [ - 'uuid' => $page1->getUuid(), - 'path' => $page1->getResourceSegment(), - ], - 'suffix' => '/test-article', - 'path' => '/test-page/articles/test-article', - ]; - - $article = $this->postPageTreeRoute(['page' => $routePathData['page']]); - - $this->documentManager->move($page1, $page2->getUuid()); - $this->documentManager->flush(); - $this->documentManager->clear(); - - $page1 = $this->documentManager->find($page1->getUuid(), 'de'); - - $this->client->jsonRequest('GET', '/api/articles/' . $article['id'] . '?locale=de'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals('Test Article', $response['title']); - $this->assertEquals('/page-2/page-1/articles/test-article', $response['route']); - $this->assertEquals( - [ - 'page' => [ - 'uuid' => $page1->getUuid(), - 'path' => $page1->getResourceSegment(), - ], - 'suffix' => '/articles/test-article', - 'path' => '/page-2/page-1/articles/test-article', - ], - $response['routePath'] - ); - } - - public function testPostPageTreeRouteGenerateRemovePage() - { - $page = $this->createPage('Test Page', '/test-page'); - - $routePathData = [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - ], - 'suffix' => '/articles/test-article', - 'path' => '/test-page/articles/test-article', - ]; - - $article = $this->postPageTreeRoute($routePathData); - - $this->documentManager->remove($page); - $this->documentManager->flush(); - $this->documentManager->clear(); - - $this->client->jsonRequest('GET', '/api/articles/' . $article['id'] . '?locale=de'); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals('Test Article', $response['title']); - $this->assertEquals('/test-page/articles/test-article', $response['route']); - $this->assertEquals( - [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getResourceSegment(), - ], - 'suffix' => '/articles/test-article', - 'path' => '/test-page/articles/test-article', - ], - $response['routePath'] - ); - } - - protected function publish($id) - { - $this->client->jsonRequest('PUT', '/api/articles/' . $id . '?action=publish&locale=de', $this->get($id)); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - public function testOrderPages() - { - $this->markTestSkipped(); - - $article = $this->post(); - $pages = [ - $this->postPage($article, 'Page 1'), - $this->postPage($article, 'Page 2'), - $this->postPage($article, 'Page 3'), - $this->postPage($article, 'Page 4'), - ]; - $this->publish($article['id']); - - $pages[] = $this->postPage($article, 'Page 5'); - - $expectedPages = [$pages[4]['id'], $pages[3]['id'], $pages[2]['id'], $pages[1]['id'], $pages[0]['id']]; - - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article['id'] . '?action=order&locale=de', - ['pages' => $expectedPages] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $response = $this->publish($article['id']); - - $responsePages = $response['children']; - for ($i = 0; $i < \count($expectedPages); ++$i) { - $this->assertEquals($expectedPages[$i], $responsePages[$i]['id']); - $this->assertEquals($i + 2, $responsePages[$i]['pageNumber']); - $this->assertEquals( - $article['route'] . '/page-' . $responsePages[$i]['pageNumber'], - $responsePages[$i]['route'] - ); - - $route = $this->findRoute($responsePages[$i]['route'], 'de'); - $this->assertTrue(\is_subclass_of($route->getEntityClass(), ArticlePageDocument::class) || ArticlePageDocument::class === $route->getEntityClass()); - $this->assertEquals($responsePages[$i]['id'], $route->getEntityId()); - $this->assertEquals('de', $route->getLocale()); - $this->assertFalse($route->isHistory()); - $this->assertNull($route->getTarget()); - } - } - - private function postPageTreeRoute($routePathData, $title = 'Test Article') - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de&action=publish', - [ - 'title' => $title, - 'template' => 'page_tree_route', - 'routePath' => $routePathData, - 'authored' => \date('c', \strtotime('2016-01-01')), - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - /** - * Create a media. - * - * @return Media - */ - private function createMedia() - { - $collection = new Collection(); - $collection->setType($this->getEntityManager()->getReference(CollectionType::class, 1)); - $media = new Media(); - $media->setType($this->getEntityManager()->getReference(MediaType::class, 1)); - $media->setCollection($collection); - - $this->getEntityManager()->persist($collection); - $this->getEntityManager()->persist($media); - $this->getEntityManager()->flush(); - - return $media; - } - - /** - * Create a category. - * - * @return Category - */ - private function createCategory() - { - $entityManager = $this->getEntityManager(); - - $category = new Category(); - $category->setDefaultLocale('de'); - $entityManager->persist($category); - $entityManager->flush(); - - return $category; - } - - /** - * Create a tag. - * - * @return Tag - */ - private function createTag() - { - $entityManager = $this->getEntityManager(); - - $tag = new Tag(); - $tag->setName('Test'); - $entityManager->persist($tag); - $entityManager->flush(); - - return $tag; - } - - /** - * Create a contact. - * - * @return Contact - */ - private function createContact() - { - $entityManager = $this->getEntityManager(); - - $contact = new Contact(); - $contact->setFirstName('Max'); - $contact->setLastName('Mustermann'); - $entityManager->persist($contact); - $entityManager->flush(); - - return $contact; - } - - /** - * Create a new page. - * - * @param string $title - * @param string $resourceSegment - * @param string $locale - * - * @return PageDocument - */ - private function createPage($title, $resourceSegment, $locale = 'de') - { - $sessionManager = $this->getContainer()->get('sulu.phpcr.session'); - - $page = $this->documentManager->create('page'); - - $uuidReflection = new \ReflectionProperty(PageDocument::class, 'uuid'); - $uuidReflection->setAccessible(true); - $uuidReflection->setValue($page, Uuid::uuid4()->toString()); - - $page->setTitle($title); - $page->setStructureType('default'); - $page->setParent($this->documentManager->find($sessionManager->getContentPath('sulu_io'))); - $page->setResourceSegment($resourceSegment); - - $this->documentManager->persist($page, $locale); - $this->documentManager->publish($page, $locale); - $this->documentManager->flush(); - - return $page; - } - - private function purgeIndex() - { - /** @var IndexerInterface $indexer */ - $indexer = $this->getContainer()->get('sulu_article.elastic_search.article_indexer'); - $indexer->clear(); - } - - private function flush() - { - /** @var IndexerInterface $indexer */ - $indexer = $this->getContainer()->get('sulu_article.elastic_search.article_indexer'); - $indexer->flush(); - } - - private function findViewDocument($uuid, $locale) - { - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - - return $manager->find( - $this->getContainer()->getParameter('sulu_article.view_document.article.class'), - $this->getViewDocumentId($uuid, $locale) - ); - } - - /** - * @param string $path - * @param string $locale - * - * @return RouteInterface - */ - private function findRoute($path, $locale) - { - return $this->getContainer()->get('sulu.repository.route')->findByPath($path, $locale); - } - - private function getRoute($title) - { - return '/articles/' . Urlizer::urlize($title); - } -} diff --git a/Tests/Functional/Controller/ArticlePageControllerTest.php b/Tests/Functional/Controller/ArticlePageControllerTest.php deleted file mode 100644 index 9c70f9f5c..000000000 --- a/Tests/Functional/Controller/ArticlePageControllerTest.php +++ /dev/null @@ -1,390 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->purgeIndex(); - - $this->purgeDatabase(); - $this->initPhpcr(); - - $collectionTypes = new LoadCollectionTypes(); - $collectionTypes->load($this->getEntityManager()); - $mediaTypes = new LoadMediaTypes(); - $mediaTypes->load($this->getEntityManager()); - } - - private function createArticle($title = 'Test-Article', $template = 'default_pages', $locale = 'de') - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=' . $locale, - [ - 'title' => $title, - 'pageTitle' => $title, - 'template' => $template, - 'authored' => \date('c', \strtotime('2016-01-01')), - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - private function createArticleLocale($article, $title = 'Test-Article', $template = 'default_pages', $locale = 'en') - { - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=' . $locale, - [ - 'title' => $title, - 'pageTitle' => $title, - 'template' => $template, - 'authored' => \date('c', \strtotime('2016-01-01')), - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - private function createArticleShadow($article, $locale = 'en', $shadowLocale = 'de') - { - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '?locale=' . $locale, - [ - 'shadowOn' => true, - 'shadowBaseLanguage' => $shadowLocale, - ] - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - private function getArticle($uuid, $locale = 'de') - { - $this->client->jsonRequest('GET', '/api/articles/' . $uuid . '?locale=' . $locale); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - private function post($article, $pageTitle = 'Test-Page', $template = 'default_pages', $locale = 'de') - { - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article['id'] . '/pages?locale=' . $locale, - [ - 'pageTitle' => $pageTitle, - 'template' => $template, - ] - ); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - public function testPost($title = 'Test-Article', $pageTitle = 'Test-Page', $template = 'default_pages') - { - $article = $this->createArticle($title, $template); - $response = $this->post($article, $pageTitle); - - $this->assertEquals($title, $response['title']); - $this->assertEquals($pageTitle, $response['pageTitle']); - $this->assertEquals($template, $response['template']); - $this->assertEquals($this->getRoute($title, 2), $response['route']); - $this->assertEquals(2, $response['pageNumber']); - - $this->assertEquals($article['id'], $response['parent']['id']); - - $article = $this->getArticle($article['id']); - - $pages = $article['children']; - - $this->assertCount(1, $pages); - $this->assertEquals($response['id'], \reset($pages)['id']); - - $articleViewDocument = $this->findViewDocument($article['id'], 'de'); - $this->assertCount(1, $articleViewDocument->getPages()); - $this->assertEquals(2, $articleViewDocument->getPages()[0]->pageNumber); - $this->assertEquals($pageTitle, $articleViewDocument->getPages()[0]->title); - $this->assertEquals($response['id'], $articleViewDocument->getPages()[0]->uuid); - } - - public function testPostMultiplePages($title = 'Test-Article') - { - $article = $this->createArticle($title); - - $response1 = $this->post($article, 'Test-1'); - $this->assertEquals($title, $response1['title']); - $this->assertEquals('Test-1', $response1['pageTitle']); - $this->assertEquals($this->getRoute($title, 2), $response1['route']); - $this->assertEquals(2, $response1['pageNumber']); - - $response2 = $this->post($article, 'Test-2'); - $this->assertEquals($title, $response2['title']); - $this->assertEquals('Test-2', $response2['pageTitle']); - $this->assertEquals($this->getRoute($title, 3), $response2['route']); - $this->assertEquals(3, $response2['pageNumber']); - - $article = $this->getArticle($article['id']); - - $pages = \array_values($article['children']); - - $this->assertCount(2, $pages); - $this->assertEquals($response1['id'], $pages[0]['id']); - $this->assertEquals($response2['id'], $pages[1]['id']); - - $articleViewDocument = $this->findViewDocument($article['id'], 'de'); - $this->assertCount(2, $articleViewDocument->getPages()); - - $this->assertEquals(2, $articleViewDocument->getPages()[0]->pageNumber); - $this->assertEquals('Test-1', $articleViewDocument->getPages()[0]->title); - $this->assertEquals($response1['id'], $articleViewDocument->getPages()[0]->uuid); - $this->assertEquals($response1['route'], $articleViewDocument->getPages()[0]->routePath); - - $this->assertEquals(3, $articleViewDocument->getPages()[1]->pageNumber); - $this->assertEquals('Test-2', $articleViewDocument->getPages()[1]->title); - $this->assertEquals($response2['id'], $articleViewDocument->getPages()[1]->uuid); - $this->assertEquals($response2['route'], $articleViewDocument->getPages()[1]->routePath); - } - - public function testGet($title = 'Test-Article', $pageTitle = 'Test-Page', $template = 'default_pages') - { - $article = $this->createArticle($title, $template); - $page = $this->post($article, $pageTitle); - - $this->client->jsonRequest('GET', '/api/articles/' . $article['id'] . '/pages/' . $page['id'] . '?locale=de'); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertEquals($title, $response['title']); - $this->assertEquals($this->getRoute($title, 2), $response['route']); - $this->assertEquals($pageTitle, $response['pageTitle']); - $this->assertEquals($template, $response['template']); - $this->assertEquals(2, $response['pageNumber']); - } - - public function testPut($title = 'Test-Article', $pageTitle = 'New-Page-Title', $template = 'default_pages') - { - $article = $this->createArticle($title, $template); - $page = $this->post($article); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '/pages/' . $page['id'] . '?locale=de', - [ - 'pageTitle' => $pageTitle, - 'article' => 'Sulu is awesome', - ] - ); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertEquals($title, $response['title']); - $this->assertEquals($this->getRoute($title, 2), $response['route']); - $this->assertEquals($pageTitle, $response['pageTitle']); - $this->assertEquals($template, $response['template']); - $this->assertEquals('Sulu is awesome', $response['article']); - $this->assertEquals(2, $response['pageNumber']); - - $articleViewDocument = $this->findViewDocument($article['id'], 'de'); - $this->assertCount(1, $articleViewDocument->getPages()); - $this->assertEquals(2, $articleViewDocument->getPages()[0]->pageNumber); - $this->assertEquals($pageTitle, $articleViewDocument->getPages()[0]->title); - $this->assertEquals($response['id'], $articleViewDocument->getPages()[0]->uuid); - } - - public function testPutPublish($title = 'Test-Article', $pageTitle = 'New-Page-Title', $template = 'default_pages') - { - $article = $this->createArticle($title, $template); - $page = $this->post($article); - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $article['id'] . '/pages/' . $page['id'] . '?locale=de&action=publish', - [ - 'pageTitle' => $pageTitle, - 'article' => 'Sulu is awesome', - ] - ); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertEquals($title, $response['title']); - $this->assertEquals($this->getRoute($title, 2), $response['route']); - $this->assertEquals($pageTitle, $response['pageTitle']); - $this->assertEquals($template, $response['template']); - $this->assertEquals('Sulu is awesome', $response['article']); - $this->assertEquals(2, $response['pageNumber']); - - $articleViewDocument = $this->findViewDocument($article['id'], 'de'); - $this->assertCount(1, $articleViewDocument->getPages()); - $this->assertEquals(2, $articleViewDocument->getPages()[0]->pageNumber); - $this->assertEquals($pageTitle, $articleViewDocument->getPages()[0]->title); - $this->assertEquals($response['id'], $articleViewDocument->getPages()[0]->uuid); - } - - public function testDelete() - { - $article = $this->createArticle(); - $page = $this->post($article); - - $this->client->jsonRequest('DELETE', '/api/articles/' . $article['id'] . '/pages/' . $page['id'] . '?locale=de'); - - $this->assertHttpStatusCode(204, $this->client->getResponse()); - - $article = $this->getArticle($article['id']); - - $this->assertCount(0, $article['children']); - - $articleViewDocument = $this->findViewDocument($article['id'], 'de'); - $this->assertCount(0, $articleViewDocument->getPages()); - } - - public function testHandleSecondLocale($title = 'Sulu ist toll') - { - $articleDE = $this->createArticle($title); - $page1 = $this->post($articleDE, 'Sulu ist toll - Page 1'); - - $articleEN = $this->createArticleLocale($articleDE, 'Sulu is great'); - - // page 1 should exists with empty pageTitle - $this->client->jsonRequest('GET', '/api/articles/' . $articleEN['id'] . '/pages/' . $page1['id'] . '?locale=en'); - - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertArrayNotHasKey('type', $response); - $this->assertEquals('', $response['pageTitle']); - } - - public function testHandleShadowArticlePageForEN($title = 'Sulu ist toll') - { - $this->markTestSkipped(); - - $articleDE = $this->createArticle($title); - $page2 = $this->post($articleDE, 'Sulu ist toll - Page 2'); - $page3 = $this->post($articleDE, 'Sulu ist toll - Page 3'); - $page4 = $this->post($articleDE, 'Sulu ist toll - Page 4'); - - $articleEN = $this->createArticleLocale($articleDE, 'Sulu is great'); - $articleShadow = $this->createArticleShadow($articleEN); - - // check the article itself - $this->assertEquals('Sulu ist toll', $articleShadow['title']); - - // load second page - $this->client->jsonRequest('GET', '/api/articles/' . $articleEN['id'] . '/pages/' . $page2['id'] . '?locale=en'); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertEquals('Sulu ist toll', $response['title']); - $this->assertTrue($response['shadowOn']); - $this->assertEquals('de', $response['shadowBaseLanguage']); - $this->assertEquals('/articles/sulu-is-great/page-2', $response['route']); - - $articleViewDocument = $this->findViewDocument($articleEN['id'], 'en'); - $this->assertEquals('en', $articleViewDocument->getLocale()); - $this->assertEquals('/articles/sulu-is-great', $articleViewDocument->getRoutePath()); - $this->assertEquals('Sulu ist toll', $articleViewDocument->getTitle()); - $this->assertEquals(LocalizationState::SHADOW, $articleViewDocument->getLocalizationState()->state); - $this->assertEquals('de', $articleViewDocument->getLocalizationState()->locale); - $this->assertCount(3, $articleViewDocument->getPages()); - $this->assertEquals('Sulu ist toll - Page 2', $articleViewDocument->getPages()[0]->title); - $this->assertEquals('Sulu ist toll - Page 3', $articleViewDocument->getPages()[1]->title); - $this->assertEquals('Sulu ist toll - Page 4', $articleViewDocument->getPages()[2]->title); - $this->assertEquals('/articles/sulu-is-great/page-2', $articleViewDocument->getPages()[0]->routePath); - $this->assertEquals('/articles/sulu-is-great/page-3', $articleViewDocument->getPages()[1]->routePath); - $this->assertEquals('/articles/sulu-is-great/page-4', $articleViewDocument->getPages()[2]->routePath); - } - - public function testHandleShadowArticlePageForDE($title = 'Sulu is great') - { - $articleEN = $this->createArticle($title, 'default_pages', 'en'); - $page2 = $this->post($articleEN, 'Sulu is great - Page 2', 'default_pages', 'en'); - $page3 = $this->post($articleEN, 'Sulu is great - Page 3', 'default_pages', 'en'); - - $articleDE = $this->createArticleLocale($articleEN, 'Sulu is great', 'default_pages', 'de'); - $articleShadow = $this->createArticleShadow($articleDE, 'de', 'en'); - - // check the article itself - $this->assertEquals('Sulu is great', $articleShadow['title']); - - // load second page - $this->client->jsonRequest('GET', '/api/articles/' . $articleDE['id'] . '/pages/' . $page2['id'] . '?locale=de'); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - $this->assertEquals('Sulu is great', $response['title']); - $this->assertEquals('Sulu is great - Page 2', $response['pageTitle']); - } - - private function purgeIndex() - { - /** @var IndexerInterface $indexer */ - $indexer = $this->getContainer()->get('sulu_article.elastic_search.article_indexer'); - $indexer->clear(); - } - - /** - * @return ArticleViewDocumentInterface - */ - private function findViewDocument($uuid, $locale) - { - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - - return $manager->find( - $this->getContainer()->getParameter('sulu_article.view_document.article.class'), - $this->getViewDocumentId($uuid, $locale) - ); - } - - private function getRoute($title, $page) - { - return '/articles/' . Urlizer::urlize($title) . '/page-' . $page; - } -} diff --git a/Tests/Functional/Controller/VersionControllerTest.php b/Tests/Functional/Controller/VersionControllerTest.php deleted file mode 100644 index 35cfedaae..000000000 --- a/Tests/Functional/Controller/VersionControllerTest.php +++ /dev/null @@ -1,131 +0,0 @@ -client = $this->createAuthenticatedClient(); - - if (!$this->getContainer()->getParameter('sulu_document_manager.versioning.enabled')) { - $this->markTestSkipped('Versioning is not enabled'); - } - - $this->initPhpcr(); - $this->documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - } - - public function testPostRestore() - { - /** @var ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('first title'); - $article->setStructureType('default'); - - $this->documentManager->persist($article, $this->locale); - $this->documentManager->publish($article, $this->locale); - $this->documentManager->flush(); - - $article = $this->documentManager->find($article->getUuid(), $this->locale); - $article->setTitle('second title'); - $this->documentManager->persist($article, $this->locale); - $this->documentManager->publish($article, $this->locale); - $this->documentManager->flush(); - - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article->getUuid() . '/versions/1_0?action=restore&locale=' . $this->locale - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - $this->assertEquals('first title', $response['title']); - } - - public function testPostRestoreInvalidVersion() - { - /** @var ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('first title'); - $article->setStructureType('default'); - - $this->documentManager->persist($article, $this->locale); - $this->documentManager->publish($article, $this->locale); - $this->documentManager->flush(); - - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article->getUuid() . '/versions/2_0?action=restore&locale=' . $this->locale - ); - - $this->assertHttpStatusCode(404, $this->client->getResponse()); - } - - public function testCGet() - { - /** @var ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('first title'); - $article->setStructureType('default'); - - $this->documentManager->persist($article, $this->locale); - $this->documentManager->publish($article, $this->locale); - $this->documentManager->flush(); - - $article = $this->documentManager->find($article->getUuid(), $this->locale); - $article->setTitle('second title'); - $this->documentManager->persist($article, $this->locale); - $this->documentManager->publish($article, $this->locale); - $this->documentManager->flush(); - - $this->client->jsonRequest( - 'GET', - '/api/articles/' . $article->getUuid() . '/versions?locale=' . $this->locale - ); - - $this->assertHttpStatusCode(200, $this->client->getResponse()); - $response = \json_decode($this->client->getResponse()->getContent(), true); - - $this->assertEquals(2, $response['total']); - - $versions = $response['_embedded']['article_versions']; - $this->assertEquals('1_1', $versions[0]['id']); - $this->assertEquals($this->locale, $versions[0]['locale']); - $this->assertEquals('1_0', $versions[1]['id']); - $this->assertEquals($this->locale, $versions[1]['locale']); - } -} diff --git a/Tests/Functional/Document/Index/ArticleIndexerTest.php b/Tests/Functional/Document/Index/ArticleIndexerTest.php deleted file mode 100644 index 7273b0823..000000000 --- a/Tests/Functional/Document/Index/ArticleIndexerTest.php +++ /dev/null @@ -1,838 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - $this->purgeDatabase(); - - $this->liveManager = $this->getContainer()->get('es.manager.live'); - $this->manager = $this->getContainer()->get('es.manager.default'); - $this->documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - $this->liveIndexer = $this->getContainer()->get('sulu_article.elastic_search.article_live_indexer'); - $this->liveIndexer->clear(); - $this->indexer = $this->getContainer()->get('sulu_article.elastic_search.article_indexer'); - $this->indexer->clear(); - } - - public function testRemove() - { - $article = $this->createArticle( - [ - 'article' => 'Test content', - ], - 'Test Article', - 'default_with_route' - ); - - $secondLocale = 'de'; - - // now add second locale - $this->updateArticle( - $article['id'], - $secondLocale, - [ - 'id' => $article['id'], - 'article' => 'Test Inhalt', - ], - 'Test Artikel Deutsch', - 'default_with_route' - ); - - /** @var ArticleDocument $articleDocument */ - $articleDocument = $this->documentManager->find($article['id']); - $this->liveIndexer->remove($articleDocument); - $this->liveIndexer->flush(); - - self::assertNull($this->findLiveViewDocument($articleDocument->getUuid(), 'de')); - self::assertNull($this->findLiveViewDocument($articleDocument->getUuid(), 'en')); - } - - public function testReplaceWithGhostData() - { - $article = $this->createArticle( - [ - 'article' => 'Test content', - ], - 'Test Article', - 'default_with_route' - ); - - $otherArticle = $this->createArticle( - [ - 'article' => 'Other content', - ], - 'Other Article', - 'default_with_route' - ); - - $articleDocumentUuid = $article['id']; - - $documentDE = $this->findViewDocument($articleDocumentUuid, 'de'); - $documentEN = $this->findViewDocument($articleDocumentUuid, 'en'); - $documentFR = $this->findViewDocument($articleDocumentUuid, 'fr'); - - $this->assertSame('Test Article', $documentEN->getTitle()); - $this->assertSame('localized', $documentEN->getLocalizationState()->state); - $this->assertNull($documentEN->getLocalizationState()->locale); - - $this->assertSame('Test Article', $documentDE->getTitle()); - $this->assertSame('ghost', $documentDE->getLocalizationState()->state); - $this->assertSame('en', $documentDE->getLocalizationState()->locale); - - $this->assertSame('Test Article', $documentFR->getTitle()); - $this->assertSame('ghost', $documentFR->getLocalizationState()->state); - $this->assertSame('en', $documentFR->getLocalizationState()->locale); - - $secondLocale = 'de'; - - // now add second locale - $this->updateArticle( - $article['id'], - $secondLocale, - [ - 'id' => $article['id'], - 'article' => 'Test Inhalt', - ], - 'Test Artikel Deutsch', - 'default_with_route' - ); - $this->updateArticle( - $otherArticle['id'], - $secondLocale, - [ - 'id' => $otherArticle['id'], - 'article' => 'Anderer Inhalt', - ], - 'Anderer Artikel Deutsch', - 'default_with_route' - ); - - /** @var ArticleDocument $articleDocument */ - $articleDocument = $this->documentManager->find($article['id']); - /** @var ArticleDocument $otherDocument */ - $otherDocument = $this->documentManager->find($otherArticle['id']); - static::setPrivateProperty($otherDocument, 'originalLocale', 'de'); // to reproduce https://github.com/sulu/SuluArticleBundle/pull/677 correctly - - $this->indexer->replaceWithGhostData($articleDocument, 'de'); - $this->indexer->replaceWithGhostData($otherDocument, 'en'); - - $this->indexer->flush(); - - $documentEN = $this->findViewDocument($articleDocument->getUuid(), 'en'); - $documentDE = $this->findViewDocument($articleDocument->getUuid(), 'de'); - $documentFR = $this->findViewDocument($articleDocument->getUuid(), 'fr'); - - $this->assertSame('localized', $documentEN->getLocalizationState()->state); - $this->assertNull($documentEN->getLocalizationState()->locale); - - $this->assertSame('ghost', $documentDE->getLocalizationState()->state); - $this->assertSame('en', $documentDE->getLocalizationState()->locale); - - $this->assertSame('ghost', $documentFR->getLocalizationState()->state); - $this->assertSame('en', $documentFR->getLocalizationState()->locale); - - /** @var ArticleDocument $otherDocument */ - $otherDocumentEN = $this->findViewDocument($otherDocument->getUuid(), 'en'); - $otherDocumentDE = $this->findViewDocument($otherDocument->getUuid(), 'de'); - $otherDocumentFR = $this->findViewDocument($otherDocument->getUuid(), 'fr'); - - $this->assertSame('localized', $otherDocumentDE->getLocalizationState()->state); - $this->assertNull($otherDocumentDE->getLocalizationState()->locale); - - $this->assertSame('ghost', $otherDocumentEN->getLocalizationState()->state); - $this->assertSame('de', $otherDocumentEN->getLocalizationState()->locale); - - $this->assertSame('ghost', $otherDocumentFR->getLocalizationState()->state); - $this->assertSame('de', $otherDocumentFR->getLocalizationState()->locale); - } - - public function testReplaceWithGhostDataUpdateExistingGhosts() - { - $article = $this->createArticle( - [ - 'article' => 'Test content', - ], - 'Test Article English', - 'default_with_route' - ); - - $this->updateArticle( - $article['id'], - 'de', - [ - 'id' => $article['id'], - 'article' => 'Test Inhalt', - ], - 'Test Artikel Deutsch', - 'default_with_route' - ); - - $this->updateArticle( - $article['id'], - 'fr', - [ - 'id' => $article['id'], - 'article' => 'Test Inhalt', - ], - 'Test Artikel French', - 'default_with_route' - ); - - $documentEN = $this->findViewDocument($article['id'], 'en'); - $this->assertSame(LocalizationState::LOCALIZED, $documentEN->getLocalizationState()->state); - $documentDE = $this->findViewDocument($article['id'], 'de'); - $this->assertSame(LocalizationState::LOCALIZED, $documentDE->getLocalizationState()->state); - $documentFR = $this->findViewDocument($article['id'], 'fr'); - $this->assertSame(LocalizationState::LOCALIZED, $documentFR->getLocalizationState()->state); - - /** @var ArticleDocument $articleDocument */ - $articleDocument = $this->documentManager->find($article['id'], 'en'); - $this->indexer->replaceWithGhostData($articleDocument, 'fr'); - $this->indexer->flush(); - - $documentEN = $this->findViewDocument($article['id'], 'en'); - $this->assertSame(LocalizationState::LOCALIZED, $documentEN->getLocalizationState()->state); - $documentDE = $this->findViewDocument($article['id'], 'de'); - $this->assertSame(LocalizationState::LOCALIZED, $documentDE->getLocalizationState()->state); - $documentFR = $this->findViewDocument($article['id'], 'fr'); - $this->assertSame(LocalizationState::GHOST, $documentFR->getLocalizationState()->state); - $this->assertSame('en', $documentFR->getLocalizationState()->locale); - - /** @var ArticleDocument $articleDocument */ - $articleDocument = $this->documentManager->find($article['id'], 'de'); - $this->indexer->replaceWithGhostData($articleDocument, 'en'); - $this->indexer->flush(); - - $documentEN = $this->findViewDocument($article['id'], 'en'); - $this->assertSame(LocalizationState::GHOST, $documentEN->getLocalizationState()->state); - $this->assertSame('de', $documentEN->getLocalizationState()->locale); - $documentDE = $this->findViewDocument($article['id'], 'de'); - $this->assertSame(LocalizationState::LOCALIZED, $documentDE->getLocalizationState()->state); - $documentFR = $this->findViewDocument($article['id'], 'fr'); - $this->assertSame(LocalizationState::GHOST, $documentFR->getLocalizationState()->state); - $this->assertSame('de', $documentFR->getLocalizationState()->locale); - } - - public function testIndexDefaultWithRoute() - { - $article = $this->createArticle( - [ - 'article' => 'Test content', - ], - 'Test Article', - 'default_with_route' - ); - - $this->liveIndexer = $this->getContainer()->get('sulu_article.elastic_search.article_live_indexer'); - - $document = $this->documentManager->find($article['id'], $this->locale); - $this->liveIndexer->index($document); - - $viewDocument = $this->findLiveViewDocument($article['id']); - $this->assertEquals($document->getUuid(), $viewDocument->getUuid()); - $this->assertEquals('/articles/test-article', $viewDocument->getRoutePath()); - $this->assertInstanceOf('\DateTime', $viewDocument->getPublished()); - $this->assertTrue($viewDocument->getPublishedState()); - $this->assertEquals('localized', $viewDocument->getLocalizationState()->state); - $this->assertNull($viewDocument->getLocalizationState()->locale); - } - - public function testIndexShadow() - { - $article = $this->createArticle( - [ - 'article' => 'Test content', - ], - 'Test Article', - 'default_with_route' - ); - - $secondLocale = 'de'; - - // now add second locale - $this->updateArticle( - $article['id'], - $secondLocale, - [ - 'id' => $article['id'], - 'article' => 'Test Inhalt', - ], - 'Test Artikel Deutsch', - 'default_with_route' - ); - - // now transform second locale to shadow - $this->updateArticle( - $article['id'], - $secondLocale, - [ - 'id' => $article['id'], - 'shadowOn' => true, - 'shadowBaseLanguage' => 'en', - ], - null, - null - ); - - $viewDocument = $this->findLiveViewDocument($article['id'], $secondLocale); - - $this->assertEquals($article['id'], $viewDocument->getUuid()); - $this->assertEquals('/articles/test-artikel-deutsch', $viewDocument->getRoutePath()); - $this->assertInstanceOf('\DateTime', $viewDocument->getPublished()); - $this->assertTrue($viewDocument->getPublishedState()); - $this->assertEquals('shadow', $viewDocument->getLocalizationState()->state); - $this->assertEquals($this->locale, $viewDocument->getLocalizationState()->locale); - $this->assertEquals($secondLocale, $viewDocument->getLocale()); - $this->assertEquals('Test Article', $viewDocument->getTitle()); - - $contentData = \json_decode($viewDocument->getContentData(), true); - $this->assertEquals($contentData['article'], 'Test content'); - - // now update the source locale - // the shadow should be update also - $this->updateArticle( - $article['id'], - $this->locale, - [ - 'id' => $article['id'], - 'article' => 'Test content - CHANGED!', - ], - 'Test Article - CHANGED!', - 'default_with_route' - ); - - $viewDocument = $this->findLiveViewDocument($article['id'], $secondLocale); - $this->assertEquals('Test Article - CHANGED!', $viewDocument->getTitle()); - - $contentData = \json_decode($viewDocument->getContentData(), true); - $this->assertEquals($contentData['article'], 'Test content - CHANGED!'); - } - - public function testUnpublishedShadows(): void - { - $article = $this->createArticle( - [ - 'article' => 'Test content', - ], - 'Test Article', - 'default_with_route' - ); - $secondLocale = 'de'; - $thirdLocale = 'fr'; - - $this->updateArticle( - $article['id'], - $secondLocale, - [ - 'id' => $article['id'], - 'article' => 'Test Inhalt', - ], - 'Test Artikel Deutsch', - 'default_with_route' - ); - $this->updateArticle( - $article['id'], - $secondLocale, - [ - 'id' => $article['id'], - 'shadowOn' => true, - 'shadowBaseLanguage' => $this->locale, - ], - null, - null - ); - - $this->updateArticle( - $article['id'], - $thirdLocale, - [ - 'id' => $article['id'], - 'article' => 'Test French Content', - ], - 'Test Artikel French', - 'default_with_route' - ); - $this->updateArticle( - $article['id'], - $thirdLocale, - [ - 'id' => $article['id'], - 'shadowOn' => true, - 'shadowBaseLanguage' => $this->locale, - ], - null, - null - ); - - self::assertNotNull($this->findLiveViewDocument($article['id'], $this->locale)); - self::assertNotNull($this->findLiveViewDocument($article['id'], $secondLocale)); - self::assertNotNull($this->findLiveViewDocument($article['id'], $thirdLocale)); - - $this->unpublishArticle($article['id'], $this->locale); - $this->unpublishArticle($article['id'], $secondLocale); - $this->unpublishArticle($article['id'], $thirdLocale); - - self::assertNull($this->findLiveViewDocument($article['id'], $this->locale)); - self::assertNull($this->findLiveViewDocument($article['id'], $secondLocale)); - self::assertNull($this->findLiveViewDocument($article['id'], $thirdLocale)); - - // publish the shadow - $this->updateArticle( - $article['id'], - $secondLocale, - [ - 'id' => $article['id'], - ], - null, - null - ); - - // only the DE shadow should be published - self::assertNull($this->findLiveViewDocument($article['id'], $this->locale)); - self::assertNotNull($this->findLiveViewDocument($article['id'], $secondLocale)); - self::assertNull($this->findLiveViewDocument($article['id'], $thirdLocale)); - } - - public function testIndexPageTreeRoute() - { - $page = $this->createPage(); - $article = $this->createArticle( - [ - 'routePath' => [ - 'page' => ['uuid' => $page->getUuid(), 'path' => $page->getResourceSegment()], - 'path' => $page->getResourceSegment() . '/test-article', - ], - ], - 'Test Article', - 'page_tree_route' - ); - - $document = $this->documentManager->find($article['id'], $this->locale); - $this->liveIndexer->index($document); - - $viewDocument = $this->findLiveViewDocument($article['id']); - $this->assertEquals($page->getUuid(), $viewDocument->getParentPageUuid()); - } - - public function testSetUnpublished() - { - $article = $this->createArticle(); - - $viewDocument = $this->liveIndexer->setUnpublished($article['id'], $this->locale); - $this->assertNull($viewDocument->getPublished()); - $this->assertFalse($viewDocument->getPublishedState()); - } - - public function testIndexTaggedProperties() - { - $data = [ - 'title' => 'Test Article Title', - 'pageTitle' => 'Test Page Title', - 'article' => '

Test Article

', - 'article_2' => '

should not be indexed

', - ]; - - if (\class_exists(ImageMapContentType::class)) { - $data['blocks'] = [ - [ - 'type' => 'title-with-article', - 'settings' => [], - 'title' => 'Test Title in Block', - 'article' => '

Test Article in Block

', - ], - ]; - } else { - $data['blocks'] = [ - [ - 'type' => 'title-with-article', - 'title' => 'Test Title in Block', - 'article' => '

Test Article in Block

', - ], - ]; - } - - $article = $this->createArticle($data, $data['title'], 'default_with_search_tags'); - $this->documentManager->clear(); - - $document = $this->documentManager->find($article['id'], $this->locale); - $this->liveIndexer->index($document); - $this->liveIndexer->flush(); - - $viewDocument = $this->findLiveViewDocument($article['id']); - $contentFields = $viewDocument->getContentFields(); - - $this->assertSame($article['id'], $viewDocument->getUuid()); - $this->assertSame($data, \json_decode($viewDocument->getContentData(), true)); - - $this->assertCount(5, $contentFields); - $this->assertContains('Test Article Title', $contentFields); - $this->assertContains('Test Page Title', $contentFields); - $this->assertContains('Test Article', $contentFields); - $this->assertContains('Test Title in Block', $contentFields); - $this->assertContains('Test Article in Block', $contentFields); - } - - public function testIndexTaggedPropertiesBlocksInBlocks(): void - { - if (!\method_exists(RouteRepositoryInterface::class, 'remove')) { - $this->markTestSkipped('Only for Sulu > 2.1.0 (requires nested blocks)'); - } - - $data = [ - 'title' => 'Test Article', - 'blocks' => [ - [ - 'type' => 'text-with-blocks', - 'settings' => [], - 'text_1' => 'Level 1 Text_1', - 'blocks_1' => [ - [ - 'type' => 'article-with-blocks', - 'settings' => [], - 'article_2' => 'Level 2 Article_1', - 'blocks_2' => [ - [ - 'type' => 'area-with-blocks', - 'settings' => [], - 'area_3' => 'Level 3 Area_1', - 'blocks_3' => [ - [ - 'type' => 'article', - 'settings' => [], - 'article_4' => 'Level 4 Article_1', - ], - ], - ], - ], - ], - ], - ], - [ - 'type' => 'text-with-blocks', - 'settings' => [], - 'text_1' => 'Level 1 Text_2', - 'blocks_1' => [ - [ - 'type' => 'article-with-blocks', - 'settings' => [], - 'article_2' => 'Level 2 Article_2', - 'blocks_2' => [ - [ - 'type' => 'area-with-blocks', - 'settings' => [], - 'area_3' => 'Level 3 Area_2', - 'blocks_3' => [ - [ - 'type' => 'article', - 'settings' => [], - 'article_4' => 'Level 4 Article_2', - ], - ], - ], - ], - ], - ], - ], - ], - ]; - - $article = $this->createArticle($data, $data['title'], 'default_blocks_in_blocks'); - $this->documentManager->clear(); - - $document = $this->documentManager->find($article['id'], $this->locale); - $this->liveIndexer->index($document); - $this->liveIndexer->flush(); - - $viewDocument = $this->findLiveViewDocument($article['id']); - $contentFields = $viewDocument->getContentFields(); - - $this->assertEquals($article['id'], $viewDocument->getUuid()); - - $this->assertCount(9, $contentFields); - $this->assertContains('Test Article', $contentFields); - $this->assertContains('Level 1 Text_1', $contentFields); - $this->assertContains('Level 2 Article_1', $contentFields); - $this->assertContains('Level 3 Area_1', $contentFields); - $this->assertContains('Level 4 Article_1', $contentFields); - $this->assertContains('Level 1 Text_2', $contentFields); - $this->assertContains('Level 2 Article_2', $contentFields); - $this->assertContains('Level 3 Area_2', $contentFields); - $this->assertContains('Level 4 Article_2', $contentFields); - } - - public function testIndexContentData() - { - $data = [ - 'title' => 'Test Article', - 'routePath' => '/test-article', - 'pageTitle' => 'Test Page Title', - 'article' => 'Test Article', - ]; - - $article = $this->createArticle($data, $data['title'], 'default_pages'); - $this->documentManager->clear(); - - $this->createArticlePage($article); - $this->documentManager->clear(); - - $document = $this->documentManager->find($article['id'], $this->locale); - $this->liveIndexer->index($document); - $this->liveIndexer->flush(); - - $viewDocument = $this->findLiveViewDocument($article['id']); - $this->assertEquals($article['id'], $viewDocument->getUuid()); - $this->assertEquals($data, \json_decode($viewDocument->getContentData(), true)); - - $this->assertProxies($data, $viewDocument->getContent(), $viewDocument->getView()); - - $this->assertCount(1, $viewDocument->getPages()); - foreach ($viewDocument->getPages() as $page) { - $this->assertProxies( - [ - 'title' => 'Test Article', - 'routePath' => '/test-article/page-2', - 'pageTitle' => 'Test-Page', - 'article' => '', - ], - $page->content, - $page->view - ); - } - } - - private function assertProxies(array $data, $contentProxy, $viewProxy) - { - $this->assertInstanceOf(\ArrayObject::class, $contentProxy); - $this->assertInstanceOf(\ArrayObject::class, $viewProxy); - - $content = \iterator_to_array($contentProxy); - $view = \iterator_to_array($viewProxy); - - $this->assertEquals($data, $content); - foreach ($data as $key => $value) { - $this->assertArrayHasKey($key, $view); - } - } - - /** - * Create a new article. - * - * @param string $title - * @param string $template - * - * @return mixed - */ - private function createArticle(array $data = [], $title = 'Test Article', $template = 'default') - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=' . $this->locale . '&action=publish', - \array_merge(['title' => $title, 'template' => $template], $data) - ); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - /** - * Update existing article. - * - * @param string $uuid - * @param string $locale - * @param string $title - * @param string $template - * - * @return mixed - */ - private function updateArticle( - $uuid, - $locale = null, - array $data = [], - $title = 'Test Article', - $template = 'default' - ) { - $requestData = $data; - - if ($title) { - $requestData['title'] = $title; - } - - if ($template) { - $requestData['template'] = $template; - } - - $this->client->jsonRequest( - 'PUT', - '/api/articles/' . $uuid . '?locale=' . ($locale ? $locale : $this->locale) . '&action=publish', - $requestData - ); - - $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - private function unpublishArticle($uuid, $locale = null) - { - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $uuid . '?locale=' . ($locale ?: $this->locale) . '&action=unpublish' - ); - - $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - /** - * Create article page. - * - * @param string $pageTitle - * @param string $template - * - * @return array - */ - private function createArticlePage( - array $article, - array $data = [], - $pageTitle = 'Test-Page', - $template = 'default_pages' - ) { - $this->client->jsonRequest( - 'POST', - '/api/articles/' . $article['id'] . '/pages?locale=' . $this->locale . '&action=publish', - \array_merge(['pageTitle' => $pageTitle, 'template' => $template], $data) - ); - $this->assertHttpStatusCode(200, $this->client->getResponse()); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - /** - * Create a new page. - * - * @param string $title - * @param string $resourceSegment - * @param string $locale - * - * @return PageDocument - */ - private function createPage($title = 'Test Page', $resourceSegment = '/test-page', $locale = 'de') - { - $sessionManager = $this->getContainer()->get('sulu.phpcr.session'); - $page = $this->documentManager->create('page'); - - $uuidReflection = new \ReflectionProperty(PageDocument::class, 'uuid'); - $uuidReflection->setAccessible(true); - $uuidReflection->setValue($page, Uuid::uuid4()->toString()); - - $page->setTitle($title); - $page->setStructureType('default'); - $page->setParent($this->documentManager->find($sessionManager->getContentPath('sulu_io'))); - $page->setResourceSegment($resourceSegment); - - $this->documentManager->persist($page, $locale); - $this->documentManager->publish($page, $locale); - $this->documentManager->flush(); - - return $page; - } - - /** - * Find view-document in live index. - * - * @param string $uuid - * @param string $locale - * - * @return ArticleViewDocument - */ - private function findLiveViewDocument($uuid, $locale = null) - { - return $this->liveManager->find( - $this->getContainer()->getParameter('sulu_article.view_document.article.class'), - $uuid . '-' . ($locale ? $locale : $this->locale) - ); - } - - /** - * Find view-document in live index. - * - * @param string $uuid - * @param string $locale - * - * @return ArticleViewDocument - */ - private function findViewDocument($uuid, $locale = null) - { - return $this->manager->find( - $this->getContainer()->getParameter('sulu_article.view_document.article.class'), - $uuid . '-' . ($locale ? $locale : $this->locale) - ); - } -} diff --git a/Tests/Functional/Export/ArticleExportTest.php b/Tests/Functional/Export/ArticleExportTest.php deleted file mode 100644 index 8bf140b88..000000000 --- a/Tests/Functional/Export/ArticleExportTest.php +++ /dev/null @@ -1,149 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - $this->purgeDatabase(); - } - - public function testExport(): void - { - $article = $this->createArticle('Test-Article', 'default', [ - 'mainWebspace' => 'sulu_io', - 'additionalWebspaces' => ['sulu_io_blog'], - 'ext' => [ - 'seo' => [ - 'title' => 'Seo Title', - ], - 'excerpt' => [ - 'title' => 'Excerpt Title', - ], - ], - ]); - - $exporter = $this->getContainer()->get('sulu_article.export.exporter'); - - $result = $exporter->export('de'); - - $expected = << - - Test-Article<\/source> - <\/target> - <\/trans-unit> -EOT; - $this->assertRegExp('/' . $expected . '/', $result); - - $expected = << - - Seo Title<\/source> - <\/target> - <\/trans-unit> -EOT; - $this->assertRegExp('/' . $expected . '/', $result); - - $expected = << - - Excerpt Title<\/source> - <\/target> - <\/trans-unit> -EOT; - $this->assertRegExp('/' . $expected . '/', $result); - - $expected = << - - default<\/source> - default<\/target> - <\/trans-unit> -EOT; - $this->assertRegExp('/' . $expected . '/', $result); - - $expected = << - - de<\/source> - de<\/target> - <\/trans-unit> -EOT; - $this->assertRegExp('/' . $expected . '/', $result); - - $expected = << - - sulu_io<\/source> - sulu_io<\/target> - <\/trans-unit> -EOT; - $this->assertRegExp('/' . $expected . '/', $result); - - $expected = << - - <\/source> - <\/target> - <\/trans-unit> -EOT; - $this->assertRegExp('/' . $expected . '/', $result); - } - - public function testExportGhostArticles(): void - { - $this->createArticle('Test-Article', 'default', [ - 'mainWebspace' => 'sulu_io', - 'additionalWebspaces' => ['sulu_io_blog'], - 'ext' => [ - 'seo' => [ - 'title' => 'Seo Title', - ], - 'excerpt' => [ - 'title' => 'Excerpt Title', - ], - ], - ]); - - $exporter = $this->getContainer()->get('sulu_article.export.exporter'); - - $result = $exporter->export('en'); - - $this->assertStringNotContainsString('trans-unit', $result); - } - - private function createArticle($title = 'Test-Article', $template = 'default', $data = []): array - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de&action=publish', - \array_merge($data, ['title' => $title, 'template' => $template]) - ); - - return \json_decode($this->client->getResponse()->getContent(), true); - } -} diff --git a/Tests/Functional/Import/ArticleImportTest.php b/Tests/Functional/Import/ArticleImportTest.php deleted file mode 100644 index c45f88bf0..000000000 --- a/Tests/Functional/Import/ArticleImportTest.php +++ /dev/null @@ -1,93 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - $this->purgeDatabase(); - } - - public function testImport(): void - { - $article = $this->createArticle('Test-Article'); - - $import = $this->getContainer()->get('sulu_article.import.importer'); - - $fileContent = \file_get_contents(__DIR__ . '/export.xliff'); - $fileContent = \str_replace('%uuid%', $article['id'], $fileContent); - \file_put_contents(__DIR__ . '/export.test.xliff', $fileContent); - - $result = $import->import('de', __DIR__ . '/export.test.xliff', null, '1.2.xliff', true); - - $this->assertSame(1, $result->getCount()); - $this->assertSame(0, $result->getFails()); - $this->assertSame(1, $result->getSuccesses()); - $this->assertSame([], $result->getFailed()); - $this->assertSame([], $result->getExceptionStore()); - - $result = $this->getArticle($article['id']); - - $this->assertSame('simple', $result['template']); - $this->assertSame('TEST TITLE', $result['title']); - $this->assertSame('

TEST DESCRIPTION

', $result['description']); - - $this->assertSame('SEO TITLE', $result['ext']['seo']['title']); - $this->assertSame('SEO DESCRIPTION', $result['ext']['seo']['description']); - $this->assertSame('SEO KEYWORDS', $result['ext']['seo']['keywords']); - $this->assertSame('http://sulu.io', $result['ext']['seo']['canonicalUrl']); - $this->assertSame(true, $result['ext']['seo']['noIndex']); - $this->assertSame(true, $result['ext']['seo']['noFollow']); - $this->assertSame(true, $result['ext']['seo']['hideInSitemap']); - - $this->assertSame('EXCERPT TITLE', $result['ext']['excerpt']['title']); - $this->assertSame('EXCERPT MORE', $result['ext']['excerpt']['more']); - $this->assertSame('EXCERPT DESCRIPTION', $result['ext']['excerpt']['description']); - $this->assertSame(['displayOption' => 'left', 'ids' => [6, 3]], $result['ext']['excerpt']['icon']); - $this->assertSame(['displayOption' => 'left', 'ids' => [6, 3]], $result['ext']['excerpt']['images']); - } - - private function createArticle( - string $title = 'Test-Article', - string $template = 'default', - array $data = [] - ): array { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=en&action=publish', - \array_merge($data, ['title' => $title, 'template' => $template]) - ); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - private function getArticle(string $id, string $locale = 'de'): array - { - $this->client->jsonRequest('GET', '/api/articles/' . $id . '?locale=' . $locale); - - return \json_decode($this->client->getResponse()->getContent(), true); - } -} diff --git a/Tests/Functional/Import/export.xliff b/Tests/Functional/Import/export.xliff deleted file mode 100644 index 17a68b5bd..000000000 --- a/Tests/Functional/Import/export.xliff +++ /dev/null @@ -1,211 +0,0 @@ - - - - - - - The technology behind Sulu 2.0.0 - TEST TITLE - - - - - Since I wanted to go to another React conference this year and it is always awesome to meet some people using our product I thought it would be super nice to combine both activities. I stumbled upon React Amsterdam, a conference in Amsterdam covering (surprise!) React. The conference looks very promising and since I know that we have quite some users in the Netherlands it should be a great match. After exchanging a few messages with the community in our Slack channel I now have two additional events I am excited to share with you.

]]> - TEST DESCRIPTION

]]>
-
- - - - - SEO TITLE - - - - - - SEO DESCRIPTION - - - - - - SEO KEYWORDS - - - - - - http://sulu.io - - - - - 0 - 1 - - - - - 0 - 1 - - - - - 0 - 1 - - - - - - EXCERPT TITLE - - - - - - EXCERPT MORE - - - - - - EXCERPT DESCRIPTION - - - - - - - - - - - [] - [] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - simple - simple - - - - - 2020-07-30T14:54:37+02:00 - 2020-07-30T14:54:37+02:00 - - - - - 2020-07-30T14:54:37+02:00 - 2020-07-30T14:54:37+02:00 - - - - - 2020-07-30T14:54:37+02:00 - 2020-07-30T14:54:37+02:00 - - - - - - - - - - - - - - - - - en - en - - - - - - - - - - - en - en - - - - - /blog/the-technology-behind-sulu-2-0-0 - /blog/the-technology-behind-sulu-2-0-0 - - - - - 2 - 2 - - - - - /cmf/articles/2020/07/the-technology-behind-sulu-2-0-0 - /cmf/articles/2020/07/the-technology-behind-sulu-2-0-0 - - - - - - - - - - - null - null - - - - - 1 - 1 - - - - - 2020-07-30T14:54:37+02:00 - 2020-07-30T14:54:37+02:00 - - -
-
- diff --git a/Tests/Functional/Infrastructure/Doctrine/Repository/ArticleRepositoryTest.php b/Tests/Functional/Infrastructure/Doctrine/Repository/ArticleRepositoryTest.php deleted file mode 100644 index 0ad77935f..000000000 --- a/Tests/Functional/Infrastructure/Doctrine/Repository/ArticleRepositoryTest.php +++ /dev/null @@ -1,324 +0,0 @@ - 'test_experimental_storage']); - $this->articleRepository = static::getContainer()->get('sulu_article.article_repository'); - } - - public function testFindOneByNotExist(): void - { - $uuid = Uuid::uuid4()->toString(); - $this->assertNull($this->articleRepository->findOneBy(['uuid' => $uuid])); - } - - public function testGetOneByNotExist(): void - { - $this->expectException(ArticleNotFoundException::class); - - $uuid = Uuid::uuid4()->toString(); - $this->articleRepository->getOneBy(['uuid' => $uuid]); - } - - public function testFindByNotExist(): void - { - $uuid = Uuid::uuid4()->toString(); - $articles = \iterator_to_array($this->articleRepository->findBy(['uuids' => [$uuid]])); - $this->assertCount(0, $articles); - } - - public function testAdd(): void - { - $uuid = Uuid::uuid4()->toString(); - $article = new Article($uuid); - - $this->articleRepository->add($article); - static::getEntityManager()->flush(); - static::getEntityManager()->clear(); - - $article = $this->articleRepository->getOneBy(['uuid' => $uuid]); - $this->assertSame($uuid, $article->getUuid()); - } - - public function testRemove(): void - { - $uuid = Uuid::uuid4()->toString(); - $article = new Article($uuid); - - $this->articleRepository->add($article); - static::getEntityManager()->flush(); - static::getEntityManager()->clear(); - - $article = $this->articleRepository->getOneBy(['uuid' => $uuid]); - $this->articleRepository->remove($article); - static::getEntityManager()->flush(); - - $this->assertNull($this->articleRepository->findOneBy(['uuid' => $uuid])); - } - - public function testCountBy(): void - { - static::purgeDatabase(); - - $this->articleRepository->add(new Article()); - $this->articleRepository->add(new Article()); - static::getEntityManager()->flush(); - static::getEntityManager()->clear(); - - $this->assertSame(2, $this->articleRepository->countBy()); - } - - public function testFindByUuids(): void - { - static::purgeDatabase(); - - $uuid = Uuid::uuid4()->toString(); - $uuid2 = Uuid::uuid4()->toString(); - $uuid3 = Uuid::uuid4()->toString(); - $article = new Article($uuid); - $article2 = new Article($uuid2); - $article3 = new Article($uuid3); - - $this->articleRepository->add($article); - $this->articleRepository->add($article2); - $this->articleRepository->add($article3); - static::getEntityManager()->flush(); - static::getEntityManager()->clear(); - - $articles = \iterator_to_array($this->articleRepository->findBy(['uuids' => [$uuid, $uuid3]])); - - $this->assertCount(2, $articles); - } - - public function testFindByLimitAndPage(): void - { - static::purgeDatabase(); - - $this->articleRepository->add(new Article()); - $this->articleRepository->add(new Article()); - $this->articleRepository->add(new Article()); - static::getEntityManager()->flush(); - static::getEntityManager()->clear(); - - $articles = \iterator_to_array($this->articleRepository->findBy(['limit' => 2, 'page' => 2])); - $this->assertCount(1, $articles); - } - - public function testFindByLocaleAndStage(): void - { - static::purgeDatabase(); - - $article = static::createArticle(); - $article2 = static::createArticle(); - $article3 = static::createArticle(); - static::createArticleContent($article, ['title' => 'Article A']); - static::createArticleContent($article, ['title' => 'Article A', 'stage' => 'live']); - static::createArticleContent($article2, ['title' => 'Article B']); - static::createArticleContent($article3, ['title' => 'Article C']); - static::createArticleContent($article3, ['title' => 'Article C', 'stage' => 'live']); - static::getEntityManager()->flush(); - static::getEntityManager()->clear(); - - $articles = \iterator_to_array($this->articleRepository->findBy(['locale' => 'en', 'stage' => 'live'])); - $this->assertCount(2, $articles); - } - - public function testCategoryFilters(): void - { - static::purgeDatabase(); - - $categoryA = static::createCategory(['key' => 'a']); - $categoryB = static::createCategory(['key' => 'b']); - - $article = static::createArticle(); - $article2 = static::createArticle(); - $article3 = static::createArticle(); - static::createArticleContent($article, ['title' => 'Article A', 'excerptCategories' => [$categoryA]]); - static::createArticleContent($article2, ['title' => 'Article B']); - static::createArticleContent($article3, ['title' => 'Article C', 'excerptCategories' => [$categoryA, $categoryB]]); - static::getEntityManager()->flush(); - $categoryAId = $categoryA->getId(); - $categoryBId = $categoryB->getId(); - static::getEntityManager()->clear(); - - $this->assertCount(2, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryKeys' => ['a', 'b'], - ]))); - - $this->assertSame(2, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryKeys' => ['a', 'b'], - ])); - - $this->assertCount(1, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryKeys' => ['a', 'b'], - 'categoryOperator' => 'AND', - ]))); - - $this->assertSame(1, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryKeys' => ['a', 'b'], - 'categoryOperator' => 'AND', - ])); - - $this->assertCount(2, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryIds' => [$categoryAId, $categoryBId], - ]))); - - $this->assertSame(2, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryIds' => [$categoryAId, $categoryBId], - ])); - - $this->assertCount(1, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryIds' => [$categoryAId, $categoryBId], - 'categoryOperator' => 'AND', - ]))); - - $this->assertSame(1, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'categoryIds' => [$categoryAId, $categoryBId], - 'categoryOperator' => 'AND', - ])); - } - - public function testTagFilters(): void - { - static::purgeDatabase(); - - $tagA = static::createTag(['name' => 'a']); - $tagB = static::createTag(['name' => 'b']); - - $article = static::createArticle(); - $article2 = static::createArticle(); - $article3 = static::createArticle(); - static::createArticleContent($article, ['title' => 'Article A', 'excerptTags' => [$tagA]]); - static::createArticleContent($article2, ['title' => 'Article B']); - static::createArticleContent($article3, ['title' => 'Article C', 'excerptTags' => [$tagA, $tagB]]); - static::getEntityManager()->flush(); - $tagAId = $tagA->getId(); - $tagBId = $tagB->getId(); - static::getEntityManager()->clear(); - - $this->assertCount(2, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagNames' => ['a', 'b'], - ]))); - - $this->assertSame(2, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagNames' => ['a', 'b'], - ])); - - $this->assertCount(1, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagNames' => ['a', 'b'], - 'tagOperator' => 'AND', - ]))); - - $this->assertSame(1, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagNames' => ['a', 'b'], - 'tagOperator' => 'AND', - ])); - - $this->assertCount(2, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagIds' => [$tagAId, $tagBId], - ]))); - - $this->assertSame(2, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagIds' => [$tagAId, $tagBId], - ])); - - $this->assertCount(1, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagIds' => [$tagAId, $tagBId], - 'tagOperator' => 'AND', - ]))); - - $this->assertSame(1, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'tagIds' => [$tagAId, $tagBId], - 'tagOperator' => 'AND', - ])); - } - - public function testFilterTemplateKeys(): void - { - static::purgeDatabase(); - - $article = static::createArticle(); - $article2 = static::createArticle(); - $article3 = static::createArticle(); - static::createArticleContent($article, ['title' => 'Article A', 'templateKey' => 'a']); - static::createArticleContent($article2, ['title' => 'Article B', 'templateKey' => 'b']); - static::createArticleContent($article3, ['title' => 'Article C', 'templateKey' => 'c']); - static::getEntityManager()->flush(); - static::getEntityManager()->clear(); - - $this->assertCount(2, \iterator_to_array($this->articleRepository->findBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'templateKeys' => ['a', 'c'], - ]))); - - $this->assertSame(2, $this->articleRepository->countBy([ - 'locale' => 'en', - 'stage' => 'draft', - 'templateKeys' => ['a', 'c'], - ])); - } -} diff --git a/Tests/Functional/Infrastructure/Sulu/Content/ArticleContentQueryBuilderTest.php b/Tests/Functional/Infrastructure/Sulu/Content/ArticleContentQueryBuilderTest.php deleted file mode 100644 index 55f9361f0..000000000 --- a/Tests/Functional/Infrastructure/Sulu/Content/ArticleContentQueryBuilderTest.php +++ /dev/null @@ -1,445 +0,0 @@ -purgeDatabase(); - $this->initPhpcr(); - - $this->documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - $this->structureManager = $this->getContainer()->get('sulu.content.structure_manager'); - $this->extensionManager = $this->getContainer()->get('sulu_page.extension.manager'); - $this->contentQuery = $this->getContainer()->get('sulu.content.query_executor'); - - $this->languageNamespace = $this->getContainer()->getParameter('sulu.content.language.namespace'); - } - - /** - * @return mixed[] - */ - public function propertiesProvider(): array - { - $documents = []; - $max = 15; - for ($i = 0; $i < $max; ++$i) { - $data = [ - 'title' => 'News ' . $i, - 'routePath' => '/news/news-' . $i, - 'ext' => [ - 'excerpt' => [ - 'title' => 'Excerpt Title ' . $i, - 'tags' => [], - ], - ], - ]; - $template = 'simple_with_route'; - - if ($i > 2 * $max / 3) { - $template = 'block'; - $data['article'] = [ - [ - 'title' => 'Block Title ' . $i, - 'article' => 'Blockarticle ' . $i, - 'type' => 'test', - 'settings' => [], - ], - [ - 'title' => 'Block Title 2 ' . $i, - 'article' => 'Blockarticle2 ' . $i, - 'type' => 'test', - 'settings' => [], - ], - ]; - } elseif ($i > $max / 3) { - $template = 'article'; - $data['article'] = 'Text article ' . $i; - } - - /** @var ArticleDocument $document */ - $document = $this->documentManager->create('article'); - $document->setTitle($data['title']); - $document->setRoutePath($data['routePath']); - $document->getStructure()->bind($data); - $document->setStructureType($template); - $document->setWorkflowStage(WorkflowStage::PUBLISHED); - - $this->documentManager->persist($document, 'en'); - $this->documentManager->publish($document, 'en'); - - $documents[$document->getUuid()] = $document; - } - - $this->documentManager->flush(); - - return $documents; - } - - public function testProperties(): void - { - $documents = $this->propertiesProvider(); - - $webspace = new Webspace(); - $webspace->setKey('sulu_io'); - $request = new Request([], [], ['_sulu' => new RequestAttributes(['webspace' => $webspace])]); - $request->headers->add(['Accept-Language' => 'en']); - $this->getContainer()->get('request_stack')->push($request); - - $builder = new ArticleContentQueryBuilder( - $this->structureManager, - $this->extensionManager, - $this->languageNamespace, - ); - $builder->init( - [ - 'ids' => \array_keys($documents), - 'properties' => [ - 'my_article' => new PropertyParameter('my_article', 'article'), - 'my_title' => new PropertyParameter('my_title', 'title'), - 'ext_title' => new PropertyParameter('ext_title', 'excerpt.title'), - 'ext_tags' => new PropertyParameter('ext_tags', 'excerpt.tags'), - ], - ], - ); - - $result = $this->contentQuery->execute('sulu_io', ['en'], $builder); - - foreach ($result as $item) { - /** @var ArticleDocument $expectedDocument */ - $expectedDocument = $documents[$item['id']]; - - $this->assertSame($expectedDocument->getUuid(), $item['id']); - $this->assertSame($expectedDocument->getChanged(), $item['changed']); - $this->assertSame($expectedDocument->getChanger(), $item['changer']); - $this->assertSame($expectedDocument->getCreated(), $item['created']); - $this->assertSame($expectedDocument->getCreator(), $item['creator']); - $this->assertSame($expectedDocument->getLocale(), $item['locale']); - $this->assertSame($expectedDocument->getStructureType(), $item['template']); - - $this->assertSame($expectedDocument->getTitle(), $item['title']); - $this->assertSame($expectedDocument->getRoutePath(), $item['routePath']); - - if ($expectedDocument->getStructure()->hasProperty('article')) { - $this->assertSame( - $expectedDocument->getStructure()->getProperty('article')->getValue(), - $item['my_article'], - ); - } - - $this->assertSame($expectedDocument->getTitle(), $item['my_title']); - $this->assertSame($expectedDocument->getExtensionsData()['excerpt']['title'], $item['ext_title']); - $this->assertSame($expectedDocument->getExtensionsData()['excerpt']['tags'], $item['ext_tags']); - } - } - - /** - * @return mixed[] - */ - private function shadowProvider(): array - { - $nodesEn = []; - $nodesDe = []; - $nodesEn = \array_merge( - $nodesEn, - $this->save( - [ - 'title' => 'Team', - 'routePath' => '/team', - ], - 'en', - ), - ); - $nodesEn = \array_merge( - $nodesEn, - $this->save( - [ - 'title' => 'Thomas', - 'routePath' => '/team/thomas', - ], - 'en', - null, - false, - null, - Structure::STATE_TEST, - ), - ); - $nodesEn = \array_merge( - $nodesEn, - $this->save( - [ - 'title' => 'Daniel', - 'routePath' => '/team/daniel', - ], - 'en', - ), - ); - $nodesEn = \array_merge( - $nodesEn, - $this->save( - [ - 'title' => 'Johannes', - 'routePath' => '/team/johannes', - ], - 'en', - null, - false, - null, - Structure::STATE_TEST, - ), - ); - $nodesEn = \array_merge( - $nodesEn, - $this->save( - [ - 'title' => 'Alex', - 'routePath' => '/team/alex', - ], - 'en', - null, - false, - null, - ), - ); - - $nodesDe = \array_merge( - $nodesDe, - $this->save( - [ - 'title' => 'Team', - 'routePath' => '/team', - ], - 'de', - $nodesEn['/team']->getUuid(), - true, - 'en', - ), - ); - $nodesDe = \array_merge( - $nodesDe, - $this->save( - [ - 'title' => 'not-important', - 'routePath' => '/team/thomas', - ], - 'de', - $nodesEn['/team/thomas']->getUuid(), - true, - 'en', - Structure::STATE_TEST, - ), - ); - $nodesDe = \array_merge( - $nodesDe, - $this->save( - [ - 'title' => 'not-important', - 'routePath' => '/team/daniel', - ], - 'de', - $nodesEn['/team/daniel']->getUuid(), - true, - 'en', - ), - ); - $nodesDe = \array_merge( - $nodesDe, - $this->save( - [ - 'title' => 'Johannes DE', - 'routePath' => '/team/johannes', - ], - 'de', - $nodesEn['/team/johannes']->getUuid(), - ), - ); - $nodesDe = \array_merge( - $nodesDe, - $this->save( - [ - 'title' => 'not-important-2', - 'routePath' => '/team/alex', - ], - 'de', - $nodesEn['/team/alex']->getUuid(), - true, - 'en', - Structure::STATE_TEST, - ), - ); - - return ['en' => $nodesEn, 'de' => $nodesDe]; - } - - public function testShadow(): void - { - $data = $this->shadowProvider(); - - $builder = new ArticleContentQueryBuilder( - $this->structureManager, - $this->extensionManager, - $this->languageNamespace, - ); - $builder->init( - [ - 'ids' => [ - $data['en']['/team/thomas']->getUuid(), - $data['en']['/team/daniel']->getUuid(), - $data['en']['/team/johannes']->getUuid(), - $data['en']['/team/alex']->getUuid(), - ], - ], - ); - - $result = $this->contentQuery->execute('sulu_io', ['en'], $builder); - $this->assertCount(4, $result); - - $items = []; - foreach ($result as $item) { - $items[$item['routePath']] = $item; - } - - $this->assertSame('/team/thomas', $items['/team/thomas']['routePath']); - $this->assertSame('Thomas', $items['/team/thomas']['title']); - $this->assertFalse($items['/team/thomas']['publishedState']); - $this->assertNull($items['/team/thomas']['published']); - - $this->assertSame('/team/daniel', $items['/team/daniel']['routePath']); - $this->assertSame('Daniel', $items['/team/daniel']['title']); - $this->assertTrue($items['/team/daniel']['publishedState']); - $this->assertNotNull($items['/team/daniel']['published']); - - $this->assertSame('/team/johannes', $items['/team/johannes']['routePath']); - $this->assertSame('Johannes', $items['/team/johannes']['title']); - $this->assertFalse($items['/team/johannes']['publishedState']); - $this->assertNull($items['/team/johannes']['published']); - - $this->assertSame('/team/alex', $items['/team/alex']['routePath']); - $this->assertSame('Alex', $items['/team/alex']['title']); - $this->assertTrue($items['/team/alex']['publishedState']); - $this->assertNotNull($items['/team/alex']['published']); - - $result = $this->contentQuery->execute('sulu_io', ['de'], $builder); - $this->assertCount(4, $result); - - $items = []; - foreach ($result as $item) { - $items[$item['routePath']] = $item; - } - - $this->assertSame('/team/thomas', $items['/team/thomas']['routePath']); - $this->assertSame('Thomas', $items['/team/thomas']['title']); - $this->assertFalse($items['/team/thomas']['publishedState']); - $this->assertNull($items['/team/thomas']['published']); - - $this->assertSame('/team/daniel', $items['/team/daniel']['routePath']); - $this->assertSame('Daniel', $items['/team/daniel']['title']); - $this->assertTrue($items['/team/daniel']['publishedState']); - $this->assertNotNull($items['/team/daniel']['published']); - - $this->assertSame('/team/johannes', $items['/team/johannes']['routePath']); - $this->assertSame('Johannes DE', $items['/team/johannes']['title']); - $this->assertTrue($items['/team/johannes']['publishedState']); - $this->assertNotNull($items['/team/johannes']['published']); - - $this->assertSame('/team/alex', $items['/team/alex']['routePath']); - $this->assertSame('Alex', $items['/team/alex']['title']); - $this->assertFalse($items['/team/alex']['publishedState']); - $this->assertNull($items['/team/alex']['published']); - } - - private function save( - $data, - $locale, - $uuid = null, - $isShadow = false, - $shadowLocale = '', - $state = WorkflowStage::PUBLISHED - ) { - if (!$isShadow) { - /* @var ArticleDocument $document */ - try { - $document = $uuid - ? $this->documentManager->find($uuid, $locale, ['load_ghost_content' => false]) - : $this->documentManager->create('article'); - } catch (DocumentNotFoundException $e) { - $document = $this->documentManager->create('article'); - } - $document->getStructure()->bind($data); - $document->setTitle($data['title']); - $document->setRoutePath($data['routePath']); - $document->setStructureType('simple_with_route'); - $document->setWorkflowStage($state); - $this->documentManager->persist($document, $locale); - } else { - $document = $this->documentManager->find($uuid, $locale, ['load_ghost_content' => false]); - $document->setShadowLocaleEnabled(true); - $document->setShadowLocale($shadowLocale); - $document->setLocale($locale); - $document->setStructureType('simple_with_route'); - $this->documentManager->persist($document, $locale); - } - - if (WorkflowStage::PUBLISHED === $state) { - $this->documentManager->publish($document, $locale); - } - - $this->documentManager->flush(); - - return [$document->getRoutePath() => $document]; - } -} diff --git a/Tests/Functional/Markup/ArticleLinkProviderTest.php b/Tests/Functional/Markup/ArticleLinkProviderTest.php deleted file mode 100644 index 7248eac63..000000000 --- a/Tests/Functional/Markup/ArticleLinkProviderTest.php +++ /dev/null @@ -1,141 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - $manager->dropAndCreateIndex(); - $manager = $this->getContainer()->get('es.manager.live'); - $manager->dropAndCreateIndex(); - - $this->articleLinkProvider = $this->getContainer()->get('sulu_article.markup.link_provider'); - } - - public function testPreload() - { - $articles = [ - $this->createArticle(), - $this->createAndPublishArticle(), - ]; - - $uuids = \array_map( - function(array $data) { - return $data['id']; - }, - $articles - ); - - $result = $this->articleLinkProvider->preload($uuids, 'de', false); - - $this->assertCount(2, $result); - $this->assertEquals($articles[0]['id'], $result[0]->getId()); - $this->assertEquals('http://test.localhost' . $articles[0]['route'], $result[0]->getUrl()); - $this->assertFalse($result[0]->isPublished()); - $this->assertEquals($articles[1]['id'], $result[1]->getId()); - $this->assertEquals('http://test.localhost' . $articles[1]['route'], $result[1]->getUrl()); - $this->assertTrue($result[1]->isPublished()); - } - - public function testPreloadPublished() - { - $articles = [ - $this->createArticle(), - $this->createAndPublishArticle(), - ]; - - $uuids = \array_map( - function(array $data) { - return $data['id']; - }, - $articles - ); - - $result = $this->articleLinkProvider->preload($uuids, 'de'); - - $this->assertCount(1, $result); - $this->assertEquals($articles[1]['id'], $result[0]->getId()); - } - - public function testPreloadMoreThan10() - { - $articles = [ - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - $this->createArticle(), - ]; - - $uuids = \array_map( - function(array $data) { - return $data['id']; - }, - $articles - ); - - $result = $this->articleLinkProvider->preload($uuids, 'de', false); - - $this->assertCount(11, $result); - } - - private function createArticle($title = 'Test-Article', $template = 'default', $data = []) - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de', - \array_merge($data, ['title' => $title, 'template' => $template]) - ); - - return \json_decode($this->client->getResponse()->getContent(), true); - } - - private function createAndPublishArticle($title = 'Test-Article', $template = 'default', $data = []) - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de&action=publish', - \array_merge($data, ['title' => $title, 'template' => $template]) - ); - - return \json_decode($this->client->getResponse()->getContent(), true); - } -} diff --git a/Tests/Functional/Reference/Provider/ArticleReferenceProviderTest.php b/Tests/Functional/Reference/Provider/ArticleReferenceProviderTest.php deleted file mode 100644 index 7cc523b0e..000000000 --- a/Tests/Functional/Reference/Provider/ArticleReferenceProviderTest.php +++ /dev/null @@ -1,146 +0,0 @@ - - */ - private $referenceRepository; - - public function setUp(): void - { - $this->purgeDatabase(); - $this->initPhpcr(); - - if (!\interface_exists(ReferenceRefresherInterface::class)) { - return; - } - - $this->articleReferenceProvider = $this->getContainer()->get('sulu_article.reference_provider'); - $this->documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - $this->referenceRepository = $this->getContainer()->get('sulu.repository.reference'); - } - - public function testUpdateReferences(): void - { - if (!\interface_exists(ReferenceRefresherInterface::class)) { - $this->markTestSkipped('References did not exist in Sulu <2.6.'); - } - - $media = $this->createMedia(); - /** @var \Sulu\Bundle\ArticleBundle\Tests\TestExtendBundle\Document\ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('Example article'); - $article->setStructureType('default_image'); - $article->getStructure()->bind(['image' => ['id' => $media->getId()]]); - $this->documentManager->persist($article, 'en'); - $this->documentManager->publish($article, 'en'); - $this->documentManager->flush(); - - $this->articleReferenceProvider->updateReferences($article, 'en', 'test'); - $this->getEntityManager()->flush(); - - /** @var Reference[] $references */ - $references = $this->referenceRepository->findBy(['referenceContext' => 'test']); - $this->assertCount(1, $references); - self::assertSame((string) $media->getId(), $references[0]->getResourceId()); - } - - public function testUpdateUnpublishedReferences(): void - { - if (!\interface_exists(ReferenceRefresherInterface::class)) { - $this->markTestSkipped('References did not exist in Sulu <2.6.'); - } - - $media = $this->createMedia(); - /** @var \Sulu\Bundle\ArticleBundle\Tests\TestExtendBundle\Document\ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('Example article'); - $article->setStructureType('default_image'); - $article->getStructure()->bind(['image' => ['id' => $media->getId()]]); - $this->documentManager->persist($article, 'en'); - $this->documentManager->publish($article, 'en'); - $this->documentManager->flush(); - - $this->documentManager->unpublish($article, 'en'); - $this->documentManager->flush(); - $this->documentManager->clear(); - - static::ensureKernelShutdown(); - static::bootKernel(['sulu.context' => SuluKernel::CONTEXT_WEBSITE]); - // refresh services from new kernel - $this->articleReferenceProvider = $this->getContainer()->get('sulu_article.reference_provider'); - $this->documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - $this->referenceRepository = $this->getContainer()->get('sulu.repository.reference'); - - /** @var ArticleDocument $article */ - $article = $this->documentManager->find($article->getUuid(), 'en', [ - 'load_ghost_content' => false, - ]); - - $this->articleReferenceProvider->updateReferences($article, 'en', 'test'); - $this->getEntityManager()->flush(); - - $references = $this->referenceRepository->findBy(['referenceContext' => 'test']); - $this->assertCount(0, $references); - } - - private function createMedia(): Media - { - $collectionType = new CollectionType(); - $collectionType->setName('Default Collection Type'); - $collectionType->setDescription('Default Collection Type'); - - $mediaType = new MediaType(); - $mediaType->setName('Default Media Type'); - - $collection = new Collection(); - $collection->setType($collectionType); - - $media = new Media(); - $media->setType($mediaType); - $media->setCollection($collection); - - $this->getEntityManager()->persist($collection); - $this->getEntityManager()->persist($collectionType); - $this->getEntityManager()->persist($mediaType); - $this->getEntityManager()->persist($media); - $this->getEntityManager()->flush(); - - return $media; - } -} diff --git a/Tests/Functional/Reference/Refresh/ArticleReferenceRefresherTest.php b/Tests/Functional/Reference/Refresh/ArticleReferenceRefresherTest.php deleted file mode 100644 index a674ae774..000000000 --- a/Tests/Functional/Reference/Refresh/ArticleReferenceRefresherTest.php +++ /dev/null @@ -1,156 +0,0 @@ - - */ - private $referenceRepository; - - public function setUp(): void - { - $this->purgeDatabase(); - $this->initPhpcr(); - - if (!\interface_exists(ReferenceRefresherInterface::class)) { - return; - } - - $this->articleReferenceRefresher = $this->getContainer()->get('sulu_article.article_reference_refresher'); - $this->documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - $this->referenceRepository = $this->getContainer()->get('sulu.repository.reference'); - } - - public function testRefreshWithoutReferences(): void - { - if (!\interface_exists(ReferenceRefresherInterface::class)) { - $this->markTestSkipped('References did not exist in Sulu <2.6.'); - } - - /** @var ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('Example article'); - $article->setStructureType('default_image'); - $this->documentManager->persist($article, 'en'); - $this->documentManager->publish($article, 'en'); - $this->documentManager->flush(); - - $count = 0; - foreach ($this->articleReferenceRefresher->refresh() as $document) { - ++$count; - } - // flush the references - $this->getEntityManager()->flush(); - $this->assertSame(3, $count); - - self::assertCount(0, $this->referenceRepository->findAll()); - } - - public function testRefresh(): void - { - if (!\interface_exists(ReferenceRefresherInterface::class)) { - $this->markTestSkipped('References did not exist in Sulu <2.6.'); - } - - $media = $this->createMedia(); - /** @var ArticleDocument $article */ - $article = $this->documentManager->create('article'); - $article->setTitle('Example article'); - $article->setStructureType('default_image'); - $article->getStructure()->bind(['image' => ['id' => $media->getId()]]); - $this->documentManager->persist($article, 'en'); - $this->documentManager->publish($article, 'en'); - $this->documentManager->flush(); - - $count = 0; - foreach ($this->articleReferenceRefresher->refresh() as $document) { - ++$count; - } - // flush the references - $this->getEntityManager()->flush(); - $this->assertSame(3, $count); - - /** @var Reference[] $references */ - $references = $this->referenceRepository->findBy([ - 'referenceResourceKey' => 'articles', - 'referenceResourceId' => $article->getUuid(), - 'referenceLocale' => 'en', - ]); - - self::assertCount(2, $references); - - self::assertSame('image', $references[0]->getReferenceProperty()); - self::assertSame((string) $media->getId(), $references[0]->getResourceId()); - self::assertSame('media', $references[0]->getResourceKey()); - self::assertSame($article->getUuid(), $references[0]->getReferenceResourceId()); - self::assertSame('articles', $references[0]->getReferenceResourceKey()); - self::assertSame('en', $references[0]->getReferenceLocale()); - self::assertSame('website', $references[0]->getReferenceContext()); - - self::assertSame('image', $references[1]->getReferenceProperty()); - self::assertSame((string) $media->getId(), $references[1]->getResourceId()); - self::assertSame('media', $references[1]->getResourceKey()); - self::assertSame($article->getUuid(), $references[1]->getReferenceResourceId()); - self::assertSame('articles', $references[1]->getReferenceResourceKey()); - self::assertSame('en', $references[1]->getReferenceLocale()); - self::assertSame('admin', $references[1]->getReferenceContext()); - } - - private function createMedia(): Media - { - $collectionType = new CollectionType(); - $collectionType->setName('Default Collection Type'); - $collectionType->setDescription('Default Collection Type'); - - $mediaType = new MediaType(); - $mediaType->setName('Default Media Type'); - - $collection = new Collection(); - $collection->setType($collectionType); - - $media = new Media(); - $media->setType($mediaType); - $media->setCollection($collection); - - $this->getEntityManager()->persist($collection); - $this->getEntityManager()->persist($collectionType); - $this->getEntityManager()->persist($mediaType); - $this->getEntityManager()->persist($media); - $this->getEntityManager()->flush(); - - return $media; - } -} diff --git a/Tests/Functional/Sitemap/ArticleSitemapProviderTest.php b/Tests/Functional/Sitemap/ArticleSitemapProviderTest.php deleted file mode 100644 index e01a62dc6..000000000 --- a/Tests/Functional/Sitemap/ArticleSitemapProviderTest.php +++ /dev/null @@ -1,99 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - $manager->dropAndCreateIndex(); - $manager = $this->getContainer()->get('es.manager.live'); - $manager->dropAndCreateIndex(); - - $this->articleSitemapProvider = $this->getContainer()->get('sulu_article.sitemap.articles'); - } - - public function testBuild() - { - $article1 = $this->createArticle('1', 'default', 'sulu_io', []); - $article2 = $this->createArticle('2', 'simple', 'test', ['sulu_io']); - $article3 = $this->createArticle('3', 'default', 'test', ['test-2']); - $article4 = $this->createArticle('4', 'default', 'sulu_io_blog', []); - - /** @var SitemapUrl[] $result */ - $result = $this->articleSitemapProvider->build(0, 'http', 'sulu_io.localhost'); - - $this->assertCount(3, $result); - $this->assertEquals('http://sulu_io.localhost' . $article1['route'], $result[0]->getLoc()); - $this->assertEquals('http://sulu_io.localhost/blog' . $article4['route'], $result[1]->getLoc()); - $this->assertEquals('http://sulu_io.localhost' . $article2['route'], $result[2]->getLoc()); - - /** @var SitemapUrl[] $result */ - $result = $this->articleSitemapProvider->build(0, 'http', 'test.localhost'); - $this->assertCount(2, $result); - $this->assertEquals('http://test.localhost' . $article2['route'], $result[0]->getLoc()); - $this->assertEquals('http://test.localhost' . $article3['route'], $result[1]->getLoc()); - - /** @var SitemapUrl[] $result */ - $result = $this->articleSitemapProvider->build(0, 'http', 'test-2.localhost'); - $this->assertCount(1, $result); - $this->assertEquals('http://test-2.localhost' . $article3['route'], $result[0]->getLoc()); - } - - private function createArticle( - $title = 'Test-Article', - $template = 'default', - $mainWebspace = null, - $additionalWebspaces = null - ) { - $data = [ - 'title' => $title, - 'template' => $template, - 'mainWebspace' => $mainWebspace, - 'additionalWebspaces' => $additionalWebspaces, - ]; - - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de&action=publish', - \array_merge($data, ['title' => $title, 'template' => $template]) - ); - - $response = $this->client->getResponse(); - $this->assertHttpStatusCode(200, $response); - - return \json_decode($this->client->getResponse()->getContent(), true); - } -} diff --git a/Tests/Functional/Teaser/ArticleTeaserProviderTest.php b/Tests/Functional/Teaser/ArticleTeaserProviderTest.php deleted file mode 100644 index c5e4dc404..000000000 --- a/Tests/Functional/Teaser/ArticleTeaserProviderTest.php +++ /dev/null @@ -1,90 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - $manager->dropAndCreateIndex(); - $manager = $this->getContainer()->get('es.manager.live'); - $manager->dropAndCreateIndex(); - } - - public function testFind() - { - $item1 = $this->createArticle('1'); - $item2 = $this->createArticle('2', 'simple'); - - /** @var TeaserProviderInterface $provider */ - $provider = $this->getContainer()->get('sulu_article.teaser.provider'); - - $result = $provider->find([$item1['id'], $item2['id']], 'de'); - - $this->assertCount(2, $result); - $this->assertEquals($item1['id'], $result[0]->getId()); - $this->assertEquals($item1['title'], $result[0]->getTitle()); - $this->assertEquals($item2['id'], $result[1]->getId()); - $this->assertEquals($item2['title'], $result[1]->getTitle()); - - $this->assertEquals(['structureType' => 'default', 'type' => 'blog'], $result[0]->getAttributes()); - $this->assertEquals(['structureType' => 'simple', 'type' => 'video'], $result[1]->getAttributes()); - } - - public function testFindWithFallback() - { - $item = $this->createArticle( - '1', - 'default_fallback', - ['medias' => ['ids' => [5, 4, 3], 'display_options' => 'top'], 'description' => 'Sulu is awesome'] - ); - - /** @var TeaserProviderInterface $provider */ - $provider = $this->getContainer()->get('sulu_article.teaser.provider'); - - $result = $provider->find([$item['id']], 'de'); - - $this->assertCount(1, $result); - $this->assertEquals($item['id'], $result[0]->getId()); - $this->assertEquals($item['title'], $result[0]->getTitle()); - $this->assertEquals($item['description'], $result[0]->getDescription()); - $this->assertEquals(5, $result[0]->getMediaId()); - } - - private function createArticle($title = 'Test-Article', $template = 'default', $data = []) - { - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=de&action=publish', - \array_merge($data, ['title' => $title, 'template' => $template]) - ); - - return \json_decode($this->client->getResponse()->getContent(), true); - } -} diff --git a/Tests/Functional/Traits/CreateArticleTrait.php b/Tests/Functional/Traits/CreateArticleTrait.php deleted file mode 100644 index 863ae859c..000000000 --- a/Tests/Functional/Traits/CreateArticleTrait.php +++ /dev/null @@ -1,75 +0,0 @@ -get('sulu_article.article_repository'); - $article = $articleRepository->createNew($data['uuid'] ?? null); - - $articleRepository->add($article); - - return $article; - } - - /** - * @param array{ - * locale?: ?string, - * stage?: ?string, - * templateKey?: ?string, - * templateData?: mixed[], - * excerptCategories?: CategoryInterface[], - * excerptTags?: TagInterface[], - * } $data - */ - public function createArticleContent(ArticleInterface $article, array $data = []): void - { - $locale = $data['locale'] ?? 'en'; - $stage = $data['stage'] ?? DimensionContentInterface::STAGE_DRAFT; - - $unlocalizedDimensionContent = $article->createDimensionContent(); - $unlocalizedDimensionContent->setStage($stage); - $article->addDimensionContent($unlocalizedDimensionContent); - - $localizedDimensionContent = $article->createDimensionContent(); - $localizedDimensionContent->setLocale($locale); - $localizedDimensionContent->setStage($stage); - - $templateKey = $data['templateKey'] ?? null; - if ($templateKey) { - $localizedDimensionContent->setTemplateKey($templateKey); - } - $localizedDimensionContent->setTemplateData($data['templateData'] ?? ['title' => '']); - $localizedDimensionContent->setExcerptCategories($data['excerptCategories'] ?? []); - $localizedDimensionContent->setExcerptTags($data['excerptTags'] ?? []); - - $article->addDimensionContent($localizedDimensionContent); - } - - abstract protected static function getEntityManager(): EntityManagerInterface; - - abstract protected static function getContainer(): ContainerInterface; -} diff --git a/Tests/Functional/Traits/CreateCategoryTrait.php b/Tests/Functional/Traits/CreateCategoryTrait.php deleted file mode 100644 index 31405b80f..000000000 --- a/Tests/Functional/Traits/CreateCategoryTrait.php +++ /dev/null @@ -1,60 +0,0 @@ -get('sulu.repository.category'); - /** @var CategoryInterface $category */ - $category = $categoryRepository->createNew(); - $category->setKey($data['key'] ?? null); - $category->setDefaultLocale($data['default_locale'] ?? 'en'); - - static::getEntityManager()->persist($category); - - return $category; - } - - /** - * @param array{ - * title?: ?string, - * locale?: ?string, - * } $data - */ - public function createCategoryTranslation(CategoryInterface $category, array $data = []): CategoryTranslationInterface - { - $categoryTranslation = new CategoryTranslation(); - $categoryTranslation->setLocale($data['locale'] ?? 'en'); - $categoryTranslation->setTranslation($data['title'] ?? ''); - $category->addTranslation($categoryTranslation); - - return $categoryTranslation; - } - - abstract protected static function getEntityManager(): EntityManagerInterface; - - abstract protected static function getContainer(): ContainerInterface; -} diff --git a/Tests/Functional/Traits/CreateTagTrait.php b/Tests/Functional/Traits/CreateTagTrait.php deleted file mode 100644 index 74d3b5969..000000000 --- a/Tests/Functional/Traits/CreateTagTrait.php +++ /dev/null @@ -1,40 +0,0 @@ -get('sulu.repository.tag'); - /** @var TagInterface $tag */ - $tag = $tagRepository->createNew(); - $tag->setName($data['name'] ?? ''); - - static::getEntityManager()->persist($tag); - - return $tag; - } - - abstract protected static function getEntityManager(): EntityManagerInterface; - - abstract protected static function getContainer(): ContainerInterface; -} diff --git a/Tests/Functional/Trash/ArticleTrashItemHandlerTest.php b/Tests/Functional/Trash/ArticleTrashItemHandlerTest.php deleted file mode 100644 index bf173370f..000000000 --- a/Tests/Functional/Trash/ArticleTrashItemHandlerTest.php +++ /dev/null @@ -1,317 +0,0 @@ -markTestSkipped('SuluTrashBundle does not exist in Sulu <2.4'); - } - - $this->documentManager = static::getContainer()->get('sulu_document_manager.document_manager'); - $this->articleTrashItemHandler = static::getContainer()->get('sulu_article.article_trash_item_handler'); - } - - public function testStoreAndRestore(): void - { - /** @var ArticleDocument $article1De */ - $article1De = $this->documentManager->create(ArticleController::DOCUMENT_TYPE); - $article1De->setTitle('test-title-de'); - $article1De->setLocale('de'); - $article1De->setCreator(101); - $article1De->setCreated(new \DateTime('1999-04-20')); - $article1De->setAuthor(202); - $article1De->setAuthored(new \DateTime('2000-04-20')); - $article1De->setStructureType('default_with_route'); - $article1De->getStructure()->bind([ - 'routePath' => 'german-route-path', - 'article' => 'german article content', - ]); - $article1De->setExtensionsData([ - 'excerpt' => [ - 'title' => 'excerpt-title-de', - ], - 'seo' => [ - 'title' => 'seo-title-de', - ], - ]); - $article1De->setMainWebspace('sulu_io'); - $article1De->setAdditionalWebspaces(['test', 'test-2']); - $this->documentManager->persist($article1De, 'de'); - - /** @var ArticleDocument $article1En */ - $article1En = $this->documentManager->find($article1De->getUuid(), 'en', ['load_ghost_content' => false]); - $article1En->setTitle('test-title-en'); - $article1En->setLocale('en'); - $article1En->setCreator(303); - $article1En->setCreated(new \DateTime('1999-04-22')); - $article1En->setAuthor(404); - $article1En->setAuthored(new \DateTime('2000-04-22')); - $article1En->setStructureType('default_with_route'); - $article1En->getStructure()->bind([ - 'routePath' => 'english-route-path', - 'article' => 'english article content', - ]); - $article1En->setExtensionsData([ - 'excerpt' => [ - 'title' => 'excerpt-title-en', - ], - 'seo' => [ - 'title' => 'seo-title-en', - ], - ]); - $article1En->setMainWebspace('sulu_io'); - $article1En->setAdditionalWebspaces(['test', 'test-2']); - $this->documentManager->persist($article1En, 'en'); - - /** @var ArticleDocument $article2De */ - $article2De = $this->documentManager->create(ArticleController::DOCUMENT_TYPE); - $article2De->setTitle('second-article'); - $article2De->setLocale('de'); - $article2De->setStructureType('default'); - $this->documentManager->persist($article2De, 'de'); - - $this->documentManager->flush(); - $originalArticleUuid = $article1De->getUuid(); - - $trashItem = $this->articleTrashItemHandler->store($article1De); - $this->documentManager->remove($article1De); - $this->documentManager->flush(); - $this->documentManager->clear(); - - static::assertSame($originalArticleUuid, $trashItem->getResourceId()); - static::assertSame('test-title-de', $trashItem->getResourceTitle()); - static::assertSame('test-title-en', $trashItem->getResourceTitle('en')); - static::assertSame('test-title-de', $trashItem->getResourceTitle('de')); - - /** @var ArticleDocument $restoredArticle */ - $restoredArticle = $this->articleTrashItemHandler->restore($trashItem); - static::assertSame($originalArticleUuid, $restoredArticle->getUuid()); - - /** @var ArticleDocument $restoredArticleDe */ - $restoredArticleDe = $this->documentManager->find($originalArticleUuid, 'de'); - static::assertSame($originalArticleUuid, $restoredArticleDe->getUuid()); - static::assertSame('test-title-de', $restoredArticleDe->getTitle()); - static::assertSame('german-route-path', $restoredArticleDe->getRoutePath()); - static::assertSame('de', $restoredArticleDe->getLocale()); - static::assertSame(101, $restoredArticleDe->getCreator()); - static::assertSame('1999-04-20T00:00:00+00:00', $restoredArticleDe->getCreated()->format('c')); - static::assertSame(202, $restoredArticleDe->getAuthor()); - static::assertSame('2000-04-20T00:00:00+00:00', $restoredArticleDe->getAuthored()->format('c')); - static::assertSame('default_with_route', $restoredArticleDe->getStructureType()); - static::assertSame('german article content', $restoredArticleDe->getStructure()->toArray()['article']); - static::assertSame('excerpt-title-de', $restoredArticleDe->getExtensionsData()['excerpt']['title']); - static::assertSame('seo-title-de', $restoredArticleDe->getExtensionsData()['seo']['title']); - static::assertSame('sulu_io', $restoredArticleDe->getMainWebspace()); - static::assertSame(['test', 'test-2'], $restoredArticleDe->getAdditionalWebspaces()); - - /** @var ArticleDocument $restoredArticleEn */ - $restoredArticleEn = $this->documentManager->find($originalArticleUuid, 'en'); - static::assertSame($originalArticleUuid, $restoredArticleEn->getUuid()); - static::assertSame('test-title-en', $restoredArticleEn->getTitle()); - static::assertSame('english-route-path', $restoredArticleEn->getRoutePath()); - static::assertSame('en', $restoredArticleEn->getLocale()); - static::assertSame(303, $restoredArticleEn->getCreator()); - static::assertSame('1999-04-20T00:00:00+00:00', $restoredArticleEn->getCreated()->format('c')); - static::assertSame(404, $restoredArticleEn->getAuthor()); - static::assertSame('2000-04-22T00:00:00+00:00', $restoredArticleEn->getAuthored()->format('c')); - static::assertSame('default_with_route', $restoredArticleEn->getStructureType()); - static::assertSame('english article content', $restoredArticleEn->getStructure()->toArray()['article']); - static::assertSame('excerpt-title-en', $restoredArticleEn->getExtensionsData()['excerpt']['title']); - static::assertSame('seo-title-en', $restoredArticleEn->getExtensionsData()['seo']['title']); - static::assertSame('sulu_io', $restoredArticleEn->getMainWebspace()); - static::assertSame(['test', 'test-2'], $restoredArticleEn->getAdditionalWebspaces()); - } - - public function testStoreAndRestoreShadowArticle(): void - { - /** @var ArticleDocument $articleDe */ - $articleDe = $this->documentManager->create(ArticleController::DOCUMENT_TYPE); - $articleDe->setTitle('target-locale-title'); - $articleDe->setLocale('de'); - $articleDe->setStructureType('default_with_route'); - $articleDe->getStructure()->bind([ - 'routePath' => 'target-locale-route-path', - 'article' => 'target locale article content', - ]); - $this->documentManager->persist($articleDe, 'de'); - - /** @var ArticleDocument $articleEn */ - $articleEn = $this->documentManager->find($articleDe->getUuid(), 'en', ['load_ghost_content' => false]); - $articleEn->setTitle('source-locale-title'); - $articleEn->setLocale('en'); - $articleEn->setStructureType('default_with_route'); - $articleEn->getStructure()->bind([ - 'routePath' => 'source-locale-route-path', - 'article' => 'source locale article content', - ]); - $articleEn->setShadowLocaleEnabled(true); - $articleEn->setShadowLocale('de'); - $this->documentManager->persist($articleEn, 'en'); - - $this->documentManager->flush(); - $originalArticleUuid = $articleDe->getUuid(); - - $trashItem = $this->articleTrashItemHandler->store($articleDe); - $this->documentManager->remove($articleDe); - $this->documentManager->flush(); - $this->documentManager->clear(); - - /** @var ArticleDocument $restoredArticle */ - $restoredArticle = $this->articleTrashItemHandler->restore($trashItem); - static::assertSame($originalArticleUuid, $restoredArticle->getUuid()); - - /** @var ArticleDocument $restoredArticleDe */ - $restoredArticleDe = $this->documentManager->find($restoredArticle->getUuid(), 'de'); - static::assertSame('target-locale-title', $restoredArticleDe->getTitle()); - static::assertSame('de', $restoredArticleDe->getLocale()); - static::assertSame('target-locale-route-path', $restoredArticleDe->getRoutePath()); - static::assertSame('target locale article content', $restoredArticleDe->getStructure()->toArray()['article']); - static::assertSame('de', $restoredArticleDe->getOriginalLocale()); - static::assertNull($restoredArticleDe->getShadowLocale()); - - /** @var ArticleDocument $restoredArticleEn */ - $restoredArticleEn = $this->documentManager->find($restoredArticle->getUuid(), 'en'); - static::assertSame('target-locale-title', $restoredArticleEn->getTitle()); - static::assertSame('de', $restoredArticleEn->getLocale()); - static::assertSame('target-locale-route-path', $restoredArticleEn->getRoutePath()); - static::assertSame('target locale article content', $restoredArticleEn->getStructure()->toArray()['article']); - static::assertSame('en', $restoredArticleEn->getOriginalLocale()); - static::assertSame('de', $restoredArticleEn->getShadowLocale()); - } - - public function testStoreAndRestorePageTreeRoute(): void - { - /** @var PageDocument $page */ - $page = $this->documentManager->create('page'); - $page->setTitle('test parent page'); - $page->setStructureType('default'); - $page->setResourceSegment('/test-parent-page'); - - $this->documentManager->persist($page, 'de', ['parent_path' => '/cmf/sulu_io/contents']); - $this->documentManager->publish($page, 'de'); - $this->documentManager->flush(); - - /** @var ArticleDocument $article1De */ - $article1De = $this->documentManager->create(ArticleController::DOCUMENT_TYPE); - $article1De->setParent($this->documentManager->find('/cmf/sulu_io/contents', 'de')); - $article1De->setTitle('test-title-de'); - $article1De->setLocale('de'); - $article1De->setStructureType('default_with_page_tree_route'); - $article1De->setRoutePath($page->getStructure()->getProperty('url')->getValue() . '/test-title-de'); - $article1De->getStructure()->bind([ - 'routePath' => [ - 'page' => [ - 'uuid' => $page->getUuid(), - 'path' => $page->getStructure()->getProperty('url')->getValue(), - ], - 'path' => $page->getStructure()->getProperty('url')->getValue() . '/test-title-de', - 'suffix' => '/test-title-de', - ], - ]); - $article1De->setMainWebspace('sulu_io'); - $this->documentManager->persist($article1De, 'de'); - - $this->documentManager->flush(); - $originalArticleUuid = $article1De->getUuid(); - - $trashItem = $this->articleTrashItemHandler->store($article1De); - $this->documentManager->remove($article1De); - $this->documentManager->flush(); - $this->documentManager->clear(); - - static::assertSame($originalArticleUuid, $trashItem->getResourceId()); - static::assertSame('test-title-de', $trashItem->getResourceTitle()); - - /** @var ArticleDocument $restoredArticle */ - $restoredArticle = $this->articleTrashItemHandler->restore($trashItem); - static::assertSame($originalArticleUuid, $restoredArticle->getUuid()); - - /** @var ArticleDocument $restoredArticleDe */ - $restoredArticleDe = $this->documentManager->find($originalArticleUuid, 'de'); - static::assertSame($originalArticleUuid, $restoredArticleDe->getUuid()); - static::assertSame('test-title-de', $restoredArticleDe->getTitle()); - static::assertSame('/test-parent-page/test-title-de', $restoredArticleDe->getRoutePath()); - static::assertSame('de', $restoredArticleDe->getLocale()); - static::assertSame('default_with_page_tree_route', $restoredArticleDe->getStructureType()); - static::assertSame('sulu_io', $restoredArticleDe->getMainWebspace()); - } - - public function testStoreAndRestorePageTreeRouteNoValidParent(): void - { - /** @var ArticleDocument $article1De */ - $article1De = $this->documentManager->create(ArticleController::DOCUMENT_TYPE); - $article1De->setParent($this->documentManager->find('/cmf/sulu_io/contents', 'de')); - $article1De->setTitle('test-title-de'); - $article1De->setLocale('de'); - $article1De->setStructureType('default_with_page_tree_route'); - $article1De->getStructure()->bind([ - 'routePath' => [ - 'page' => [ - 'uuid' => 'not-existing-uuid', - 'path' => '/not-existing-path', - ], - 'path' => '/not-existing-path/test-title-de', - 'suffix' => '/test-title-de', - ], - ]); - $article1De->setMainWebspace('sulu_io'); - $this->documentManager->persist($article1De, 'de'); - - $this->documentManager->flush(); - $originalArticleUuid = $article1De->getUuid(); - - $trashItem = $this->articleTrashItemHandler->store($article1De); - $this->documentManager->remove($article1De); - $this->documentManager->flush(); - $this->documentManager->clear(); - - static::assertSame($originalArticleUuid, $trashItem->getResourceId()); - static::assertSame('test-title-de', $trashItem->getResourceTitle()); - - /** @var ArticleDocument $restoredArticle */ - $restoredArticle = $this->articleTrashItemHandler->restore($trashItem); - static::assertSame($originalArticleUuid, $restoredArticle->getUuid()); - - /** @var ArticleDocument $restoredArticleDe */ - $restoredArticleDe = $this->documentManager->find($originalArticleUuid, 'de'); - static::assertSame($originalArticleUuid, $restoredArticleDe->getUuid()); - static::assertSame('test-title-de', $restoredArticleDe->getTitle()); - static::assertSame('/not-existing-path/test-title-de', $restoredArticleDe->getRoutePath()); - static::assertSame('de', $restoredArticleDe->getLocale()); - static::assertSame('default_with_page_tree_route', $restoredArticleDe->getStructureType()); - static::assertSame('sulu_io', $restoredArticleDe->getMainWebspace()); - } -} diff --git a/Tests/Functional/Twig/ArticleViewDocumentTwigExtensionTest.php b/Tests/Functional/Twig/ArticleViewDocumentTwigExtensionTest.php deleted file mode 100644 index bae5c5f77..000000000 --- a/Tests/Functional/Twig/ArticleViewDocumentTwigExtensionTest.php +++ /dev/null @@ -1,157 +0,0 @@ -client = $this->createAuthenticatedClient(); - - $this->initPhpcr(); - - /** @var Manager $manager */ - $manager = $this->getContainer()->get('es.manager.default'); - $manager->dropAndCreateIndex(); - $manager = $this->getContainer()->get('es.manager.live'); - $manager->dropAndCreateIndex(); - } - - public function testFindMethods() - { - $items = [ - $this->createArticle('XXX 1'), - $this->createArticle('XXX 2'), - $this->createArticle('YYY 3'), - $this->createArticle('YYY 4'), - $this->createArticle('XXX 3 - in another webspace', 'default', 'test', []), - ]; - - $this->pushFakeRequest('sulu_io', $items[0]['id']); - - // test 'loadRecent' => all others should be returned - $result = $this->getTwigExtension()->loadRecent(); - $this->assertCount(3, $result); - - // test 'loadSimilar' => only article with title 'XXX 2' should be returned - $result = $this->getTwigExtension()->loadSimilar(); - $this->assertCount(1, $result); - $this->assertEquals($items[1]['title'], $result[0]->getTitle()); - } - - public function testFindMethodsWithIgnoreWebspaces() - { - $items = [ - $this->createArticle('XXX 1'), - $this->createArticle('XXX 2'), - $this->createArticle('YYY 3'), - $this->createArticle('YYY 4'), - $this->createArticle('XXX 3 - in another webspace', 'default', 'test', []), - ]; - - $this->pushFakeRequest('sulu_io', $items[0]['id']); - - // test 'loadRecent' => all others should be returned - $result = $this->getTwigExtension()->loadRecent(10, null, null, true); - $this->assertCount(4, $result); - - // test 'loadSimilar' => only article with title 'XXX 2' and 'XXX 3' should be returned - $result = $this->getTwigExtension()->loadSimilar(10, null, null, true); - $this->assertCount(2, $result); - $this->assertEquals($items[1]['title'], $result[0]->getTitle()); - $this->assertEquals($items[4]['title'], $result[1]->getTitle()); - } - - private function createArticle( - $title = 'Test-Article', - $template = 'default', - $mainWebspace = null, - $additionalWebspaces = null - ) { - $data = [ - 'title' => $title, - 'template' => $template, - ]; - - if ($mainWebspace) { - $data['mainWebspace'] = $mainWebspace; - $data['additionalWebspaces'] = $additionalWebspaces; - } - - $this->client->jsonRequest( - 'POST', - '/api/articles?locale=' . self::LOCALE . '&action=publish', - $data - ); - - $respone = $this->client->getResponse(); - $this->assertHttpStatusCode(200, $respone); - - return \json_decode($respone->getContent(), true); - } - - private function pushFakeRequest($webspaceKey, $id) - { - $webspaceManager = $this->getContainer()->get('sulu_core.webspace.webspace_manager'); - $webspace = $webspaceManager->findWebspaceByKey($webspaceKey); - - $fakeRequest = Request::create('/', 'GET'); - $fakeRequest->setLocale('de'); - $fakeRequest->attributes->set('_sulu', new RequestAttributes( - [ - 'webspace' => $webspace, - ] - )); - $fakeRequest->attributes->set('object', $this->getArticleDocument($id)); - - /** @var RequestStack $requestStack */ - $requestStack = $this->getContainer()->get('request_stack'); - $requestStack->push($fakeRequest); - } - - /** - * @param string $uuid - * - * @return ArticleDocument - */ - private function getArticleDocument($uuid) - { - $documentManager = $this->getContainer()->get('sulu_document_manager.document_manager'); - - return $documentManager->find($uuid, self::LOCALE); - } - - /** - * @return ArticleViewDocumentTwigExtension - */ - private function getTwigExtension() - { - return $this->getContainer()->get('sulu_article.twig.view_document_repository'); - } -} diff --git a/Tests/TestExtendBundle/Document/ArticleDocument.php b/Tests/TestExtendBundle/Document/ArticleDocument.php deleted file mode 100644 index b53b960a0..000000000 --- a/Tests/TestExtendBundle/Document/ArticleDocument.php +++ /dev/null @@ -1,18 +0,0 @@ -prophesize(Manager::class); - $property = $this->prophesize(PropertyInterface::class); - $structure = $this->prophesize(StructureInterface::class); - $repository = $this->prophesize(Repository::class); - $search = $this->prophesize(Search::class); - $referenceStore = $this->prophesize(ReferenceStoreInterface::class); - - $structure->getLanguageCode()->willReturn('de'); - $property->getStructure()->willReturn($structure->reveal()); - - $property->getValue()->willReturn($ids); - $manager->getRepository(ArticleViewDocument::class)->willReturn($repository->reveal()); - $repository->createSearch()->willReturn($search->reveal()); - $search->addQuery( - Argument::that( - function(IdsQuery $query) use ($ids) { - return $query->toArray() === [ - 'ids' => [ - 'values' => \array_map( - function($id) { - return $id . '-de'; - }, - $ids - ), - ], - ]; - } - ) - )->shouldBeCalled(); - $search->setSize(2)->shouldBeCalled(); - - $repository->findDocuments($search->reveal())->willReturn($articles); - - $contentType = new ArticleSelectionContentType( - $manager->reveal(), - $referenceStore->reveal(), - ArticleViewDocument::class - ); - - $result = $contentType->getContentData($property->reveal()); - - $this->assertCount(2, $result); - $this->assertEquals($ids[0], $result[0]->getUuid()); - $this->assertEquals($ids[1], $result[1]->getUuid()); - } - - public function testGetContentDataEmptyArray() - { - $ids = []; - - $manager = $this->prophesize(Manager::class); - $property = $this->prophesize(PropertyInterface::class); - $referenceStore = $this->prophesize(ReferenceStoreInterface::class); - - $property->getValue()->willReturn($ids); - $manager->getRepository(ArticleViewDocument::class)->shouldNotBeCalled(); - - $contentType = new ArticleSelectionContentType( - $manager->reveal(), - $referenceStore->reveal(), - ArticleViewDocument::class - ); - - $result = $contentType->getContentData($property->reveal()); - - $this->assertCount(0, $result); - } - - public function testGetContentDataNull() - { - $ids = null; - - $manager = $this->prophesize(Manager::class); - $property = $this->prophesize(PropertyInterface::class); - $referenceStore = $this->prophesize(ReferenceStoreInterface::class); - - $property->getValue()->willReturn($ids); - $manager->getRepository(ArticleViewDocument::class)->shouldNotBeCalled(); - - $contentType = new ArticleSelectionContentType( - $manager->reveal(), - $referenceStore->reveal(), - ArticleViewDocument::class - ); - - $result = $contentType->getContentData($property->reveal()); - - $this->assertCount(0, $result); - } -} diff --git a/Tests/Unit/Content/SingleArticleSelectionContentTypeTest.php b/Tests/Unit/Content/SingleArticleSelectionContentTypeTest.php deleted file mode 100644 index f54720923..000000000 --- a/Tests/Unit/Content/SingleArticleSelectionContentTypeTest.php +++ /dev/null @@ -1,83 +0,0 @@ -prophesize(Manager::class); - $property = $this->prophesize(PropertyInterface::class); - $structure = $this->prophesize(StructureInterface::class); - $repository = $this->prophesize(Repository::class); - $referenceStore = $this->prophesize(ReferenceStoreInterface::class); - - $structure->getLanguageCode()->willReturn($locale); - $property->getStructure()->willReturn($structure->reveal()); - - $property->getValue()->willReturn($id); - $manager->getRepository(ArticleViewDocument::class)->willReturn($repository->reveal()); - $repository->find($localizedId)->willReturn($article); - $repository->find($localizedId)->shouldBeCalled(); - - $contentType = new SingleArticleSelectionContentType( - $manager->reveal(), - $referenceStore->reveal(), - ArticleViewDocument::class - ); - - $result = $contentType->getContentData($property->reveal()); - - $this->assertNotNull($result); - $this->assertIsObject($result); - $this->assertEquals($id, $result->getUuid()); - } - - public function testGetContentDataNull() - { - $id = null; - - $manager = $this->prophesize(Manager::class); - $property = $this->prophesize(PropertyInterface::class); - $referenceStore = $this->prophesize(ReferenceStoreInterface::class); - - $property->getValue()->willReturn($id); - $manager->getRepository(ArticleViewDocument::class)->shouldNotBeCalled(); - - $contentType = new SingleArticleSelectionContentType( - $manager->reveal(), - $referenceStore->reveal(), - ArticleViewDocument::class - ); - - $result = $contentType->getContentData($property->reveal()); - - $this->assertNull($result); - } -} diff --git a/Tests/Unit/DependencyInjection/WebspaceSettingsConfigurationResolverTest.php b/Tests/Unit/DependencyInjection/WebspaceSettingsConfigurationResolverTest.php deleted file mode 100644 index 4643dfab2..000000000 --- a/Tests/Unit/DependencyInjection/WebspaceSettingsConfigurationResolverTest.php +++ /dev/null @@ -1,101 +0,0 @@ - 'example1', - ], - [ - [], - ], - 'example1', - [], - ], - // Case 2 - [ - [ - 'default' => 'example1', - ], - [ - ['test1', 'test2'], - ], - 'example1', - [], - ], - // Case 3 - [ - [ - 'default' => 'example1', - 'de' => 'test1', - ], - [ - 'default' => ['test1', 'test2'], - 'de' => ['example1'], - ], - 'test1', - ['example1'], - ], - // Case 4 - [ - [ - 'default' => 'example1', - 'de' => 'test1', - ], - [ - 'default' => ['test1', 'test2'], - 'de' => ['example1'], - ], - 'test1', - ['example1'], - ], - // Case 5 - [ - [ - 'default' => 'example1', - 'en' => 'test1', - ], - [ - 'default' => ['test1', 'test2'], - 'en' => ['example1'], - ], - 'example1', - ['test1', 'test2'], - ], - ]; - } - - /** - * @param string[] $expectedResultAdditionalWebspaces - * - * @dataProvider configuration - */ - public function test( - array $defaultMainWebspaceConfig, - array $defaultAdditionalWebspaceConfig, - $expectedResultMainWebspace, - array $expectedResultAdditionalWebspaces - ) { - $web = new WebspaceSettingsConfigurationResolver($defaultMainWebspaceConfig, $defaultAdditionalWebspaceConfig); - $this->assertEquals($expectedResultMainWebspace, $web->getDefaultMainWebspaceForLocale('de')); - $this->assertEquals($expectedResultAdditionalWebspaces, $web->getDefaultAdditionalWebspacesForLocale('de')); - } -} diff --git a/Tests/Unit/Document/Serializer/WebsiteArticleUrlsSubscriberTest.php b/Tests/Unit/Document/Serializer/WebsiteArticleUrlsSubscriberTest.php deleted file mode 100644 index c7d42004a..000000000 --- a/Tests/Unit/Document/Serializer/WebsiteArticleUrlsSubscriberTest.php +++ /dev/null @@ -1,307 +0,0 @@ -requestStack = $this->prophesize(RequestStack::class); - $this->routeRepository = $this->prophesize(RouteRepository::class); - $this->webspaceManager = $this->prophesize(WebspaceManagerInterface::class); - $this->documentInspector = $this->prophesize(DocumentInspector::class); - $this->documentRegistry = $this->prophesize(DocumentRegistry::class); - $this->nodeManager = $this->prophesize(NodeManager::class); - - $this->urlsSubscriber = new WebsiteArticleUrlsSubscriber( - $this->requestStack->reveal(), - $this->routeRepository->reveal(), - $this->webspaceManager->reveal(), - $this->documentInspector->reveal(), - $this->documentRegistry->reveal(), - $this->nodeManager->reveal() - ); - - $webspace = new Webspace(); - $webspace->addLocalization(new Localization('en')); - $webspace->addLocalization(new Localization('de')); - - $request = $this->prophesize(Request::class); - $request->get('_sulu')->willReturn(new RequestAttributes(['webspace' => $webspace])); - $this->requestStack->getCurrentRequest()->willReturn($request->reveal()); - } - - public function testAddUrlsOnPostSerialize() - { - $article = $this->prophesize(ArticleDocument::class); - $visitor = $this->prophesize(SerializationVisitorInterface::class); - - $context = $this->prophesize(SerializationContext::class); - $context->hasAttribute('urls')->willReturn(true); - - $entityId = '123-123-123'; - $article->getUuid()->willReturn($entityId); - - $event = $this->prophesize(ObjectEvent::class); - $event->getObject()->willReturn($article->reveal()); - $event->getVisitor()->willReturn($visitor->reveal()); - $event->getContext()->willReturn($context->reveal()); - - $entityClass = \get_class($article->reveal()); - - $this->documentRegistry->hasDocument($article->reveal())->willReturn(true); - $this->documentInspector->getPublishedLocales($article->reveal())->willReturn(['en', 'de']); - - $deRoute = $this->prophesize(RouteInterface::class); - $deRoute->getPath()->willReturn('/seite'); - $this->routeRepository->findByEntity($entityClass, $entityId, 'de')->willReturn($deRoute->reveal()); - $this->webspaceManager->findUrlByResourceLocator('/seite', null, 'de')->willReturn('http://sulu.io/de/seite'); - - $enRoute = $this->prophesize(RouteInterface::class); - $enRoute->getPath()->willReturn('/page'); - $this->routeRepository->findByEntity($entityClass, $entityId, 'en')->willReturn($enRoute->reveal()); - $this->webspaceManager->findUrlByResourceLocator('/page', null, 'en')->willReturn('http://sulu.io/page'); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'urls' === $metadata->name; - }), - ['de' => '/seite', 'en' => '/page'] - )->shouldBeCalled(); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'localizations' === $metadata->name; - }), - [ - 'de' => ['locale' => 'de', 'url' => 'http://sulu.io/de/seite', 'country' => '', 'alternate' => true], - 'en' => ['locale' => 'en', 'url' => 'http://sulu.io/page', 'country' => '', 'alternate' => true], - ] - )->shouldBeCalled(); - - $this->urlsSubscriber->addUrlsOnPostSerialize($event->reveal()); - } - - public function testAddUrlsOnPostSerializeUnregisteredDocument() - { - $article = $this->prophesize(ArticleDocument::class); - $node = $this->prophesize(NodeInterface::class); - $visitor = $this->prophesize(SerializationVisitorInterface::class); - - $context = $this->prophesize(SerializationContext::class); - $context->hasAttribute('urls')->willReturn(true); - - $entityId = '123-123-123'; - $locale = 'en'; - $article->getUuid()->willReturn($entityId); - $article->getLocale()->willReturn($locale); - - $event = $this->prophesize(ObjectEvent::class); - $event->getObject()->willReturn($article->reveal()); - $event->getVisitor()->willReturn($visitor->reveal()); - $event->getContext()->willReturn($context->reveal()); - - $entityClass = \get_class($article->reveal()); - - $this->documentRegistry->hasDocument($article->reveal())->willReturn(false); - $this->nodeManager->find($entityId)->willReturn($node->reveal())->shouldBeCalled(); - $this->documentRegistry->registerDocument($article->reveal(), $node->reveal(), $locale)->shouldBeCalled(); - - $this->documentInspector->getPublishedLocales($article->reveal())->willReturn(['en', 'de']); - - $deRoute = $this->prophesize(RouteInterface::class); - $deRoute->getPath()->willReturn('/seite'); - $this->routeRepository->findByEntity($entityClass, $entityId, 'de')->willReturn($deRoute->reveal()); - $this->webspaceManager->findUrlByResourceLocator('/seite', null, 'de')->willReturn('http://sulu.io/de/seite'); - - $enRoute = $this->prophesize(RouteInterface::class); - $enRoute->getPath()->willReturn('/page'); - $this->routeRepository->findByEntity($entityClass, $entityId, 'en')->willReturn($enRoute->reveal()); - $this->webspaceManager->findUrlByResourceLocator('/page', null, 'en')->willReturn('http://sulu.io/page'); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'urls' === $metadata->name; - }), - ['de' => '/seite', 'en' => '/page'] - )->shouldBeCalled(); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'localizations' === $metadata->name; - }), - [ - 'de' => ['locale' => 'de', 'url' => 'http://sulu.io/de/seite', 'country' => '', 'alternate' => true], - 'en' => ['locale' => 'en', 'url' => 'http://sulu.io/page', 'country' => '', 'alternate' => true], - ] - )->shouldBeCalled(); - - $this->urlsSubscriber->addUrlsOnPostSerialize($event->reveal()); - } - - public function testAddUrlsOnPostSerializeNonExistingRoute() - { - $article = $this->prophesize(ArticleDocument::class); - $visitor = $this->prophesize(SerializationVisitorInterface::class); - - $context = $this->prophesize(SerializationContext::class); - $context->hasAttribute('urls')->willReturn(true); - - $entityId = '123-123-123'; - $article->getUuid()->willReturn($entityId); - - $event = $this->prophesize(ObjectEvent::class); - $event->getObject()->willReturn($article->reveal()); - $event->getVisitor()->willReturn($visitor->reveal()); - $event->getContext()->willReturn($context->reveal()); - - $entityClass = \get_class($article->reveal()); - - $this->documentRegistry->hasDocument($article->reveal())->willReturn(true); - $this->documentInspector->getPublishedLocales($article->reveal())->willReturn(['en', 'de']); - - $deRoute = $this->prophesize(RouteInterface::class); - $deRoute->getPath()->willReturn('/seite'); - $this->routeRepository->findByEntity($entityClass, $entityId, 'de')->willReturn($deRoute->reveal()); - $this->webspaceManager->findUrlByResourceLocator('/seite', null, 'de')->willReturn('http://sulu.io/de/seite'); - - $enRoute = $this->prophesize(RouteInterface::class); - $enRoute->getPath()->willReturn('/page'); - $this->routeRepository->findByEntity($entityClass, $entityId, 'en')->willReturn(null); - $this->webspaceManager->findUrlByResourceLocator('/', null, 'en')->willReturn('http://sulu.io/'); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'urls' === $metadata->name; - }), - ['de' => '/seite', 'en' => '/'] - )->shouldBeCalled(); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'localizations' === $metadata->name; - }), - [ - 'de' => ['locale' => 'de', 'url' => 'http://sulu.io/de/seite', 'country' => '', 'alternate' => true], - 'en' => ['locale' => 'en', 'url' => 'http://sulu.io/', 'country' => '', 'alternate' => false], - ] - )->shouldBeCalled(); - - $this->urlsSubscriber->addUrlsOnPostSerialize($event->reveal()); - } - - public function testAddUrlsOnPostSerializeUnpublishedLocale() - { - $article = $this->prophesize(ArticleDocument::class); - $visitor = $this->prophesize(SerializationVisitorInterface::class); - - $context = $this->prophesize(SerializationContext::class); - $context->hasAttribute('urls')->willReturn(true); - - $entityId = '123-123-123'; - $article->getUuid()->willReturn($entityId); - - $event = $this->prophesize(ObjectEvent::class); - $event->getObject()->willReturn($article->reveal()); - $event->getVisitor()->willReturn($visitor->reveal()); - $event->getContext()->willReturn($context->reveal()); - - $entityClass = \get_class($article->reveal()); - - $this->documentRegistry->hasDocument($article->reveal())->willReturn(true); - $this->documentInspector->getPublishedLocales($article->reveal())->willReturn(['de']); - - $deRoute = $this->prophesize(RouteInterface::class); - $deRoute->getPath()->willReturn('/seite'); - $this->routeRepository->findByEntity($entityClass, $entityId, 'de')->willReturn($deRoute->reveal()); - $this->webspaceManager->findUrlByResourceLocator('/seite', null, 'de')->willReturn('http://sulu.io/de/seite'); - - $this->routeRepository->findByEntity(Argument::any())->shouldNotBeCalled(); - $this->webspaceManager->findUrlByResourceLocator('/', null, 'en')->willReturn('http://sulu.io/'); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'urls' === $metadata->name; - }), - ['de' => '/seite', 'en' => '/'] - )->shouldBeCalled(); - - $visitor->visitProperty( - Argument::that(function(StaticPropertyMetadata $metadata) { - return 'localizations' === $metadata->name; - }), - [ - 'de' => ['locale' => 'de', 'url' => 'http://sulu.io/de/seite', 'country' => '', 'alternate' => true], - 'en' => ['locale' => 'en', 'url' => 'http://sulu.io/', 'country' => '', 'alternate' => false], - ] - )->shouldBeCalled(); - - $this->urlsSubscriber->addUrlsOnPostSerialize($event->reveal()); - } -} diff --git a/Tests/Unit/Document/Subscriber/ArticlePageSubscriberTest.php b/Tests/Unit/Document/Subscriber/ArticlePageSubscriberTest.php deleted file mode 100644 index 2250f8656..000000000 --- a/Tests/Unit/Document/Subscriber/ArticlePageSubscriberTest.php +++ /dev/null @@ -1,304 +0,0 @@ -factory = $this->prophesize(StructureMetadataFactoryInterface::class); - $this->documentManager = $this->prophesize(DocumentManagerInterface::class); - $this->documentInspector = $this->prophesize(DocumentInspector::class); - $this->slugifier = $this->prophesize(SlugifierInterface::class); - $this->nameResolver = $this->prophesize(NameResolver::class); - $this->metadata = $this->prophesize(StructureMetadata::class); - $this->document = $this->prophesize(ArticlePageDocument::class); - $this->parentDocument = $this->prophesize(ArticleDocument::class); - - $this->document->getStructureType()->willReturn('default'); - $this->factory->getStructureMetadata('article_page', 'default')->willReturn($this->metadata->reveal()); - - $this->slugifier->slugify(Argument::type('string'))->will( - function($arguments) { - return Urlizer::urlize($arguments[0]); - } - ); - $this->nameResolver->resolveName(Argument::type(NodeInterface::class), Argument::type('string'))->will( - function($arguments) { - return $arguments[1]; - } - ); - - $this->subscriber = new ArticlePageSubscriber( - $this->factory->reveal(), - $this->documentManager->reveal(), - $this->documentInspector->reveal(), - $this->slugifier->reveal(), - $this->nameResolver->reveal() - ); - } - - private function createEvent($className, $node = null, $accessor = null, $options = null) - { - $event = $this->prophesize($className); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getLocale()->willReturn($this->locale); - - if (null !== $node) { - $event->getNode()->willReturn($node); - } - - if (null !== $accessor) { - $event->getAccessor()->willReturn($accessor); - } - - if (null !== $options) { - $event->getOptions()->willReturn($options); - } - - return $event->reveal(); - } - - public function testSetTitleOnPersist() - { - $event = $this->createEvent(PersistEvent::class); - - $this->parentDocument->getTitle()->willReturn('Test title'); - $this->document->getParent()->willReturn($this->parentDocument->reveal()); - - $this->document->setTitle('Test title')->shouldBeCalled(); - - $this->subscriber->setTitleOnPersist($event); - } - - public function testSetWorkflowStageOnArticle() - { - $this->document->getParent()->willReturn($this->parentDocument->reveal()); - - $this->documentInspector->getLocalizationState($this->parentDocument->reveal())->willReturn(LocalizationState::LOCALIZED); - $this->documentInspector->getLocale($this->document->reveal())->willReturn($this->locale); - - $this->parentDocument->setWorkflowStage(WorkflowStage::TEST)->shouldBeCalled(); - $this->documentManager->persist($this->parentDocument->reveal(), $this->locale, Argument::any())->shouldBeCalled(); - - $this->subscriber->setWorkflowStageOnArticle($this->createEvent(PersistEvent::class, null, null, [])); - } - - public function testSetWorkflowStageOnArticleGhost() - { - $this->document->getParent()->willReturn($this->parentDocument->reveal()); - - $this->documentInspector->getLocalizationState($this->parentDocument->reveal())->willReturn(LocalizationState::GHOST); - - $this->parentDocument->setWorkflowStage(WorkflowStage::TEST)->shouldNotBeCalled(); - $this->documentManager->persist($this->parentDocument->reveal(), $this->locale, Argument::any())->shouldNotBeCalled(); - - $this->subscriber->setWorkflowStageOnArticle($this->createEvent(PersistEvent::class)); - } - - public function testSetNodeOnPersist() - { - $node = $this->prophesize(NodeInterface::class); - - $parentNode = $this->prophesize(NodeInterface::class); - $parentNode->addNode(Argument::type('string'))->shouldBeCalled()->willReturn($node->reveal()); - - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->hasNode()->willReturn(false); - $event->getParentNode()->willReturn($parentNode->reveal()); - $event->setNode($node->reveal())->shouldBeCalled(); - - $this->subscriber->setNodeOnPersist($event->reveal()); - } - - public function testSetNodeOnPersistWithTag() - { - $property = $this->prophesize(PropertyMetadata::class); - $property->getName()->willReturn('pageTitle'); - - $this->metadata->hasPropertyWithTagName(ArticlePageSubscriber::PAGE_TITLE_TAG_NAME) - ->willReturn(true); - $this->metadata->getPropertyByTagName(ArticlePageSubscriber::PAGE_TITLE_TAG_NAME) - ->willReturn($property->reveal()); - $node = $this->prophesize(NodeInterface::class); - - $parentNode = $this->prophesize(NodeInterface::class); - $parentNode->addNode(Urlizer::urlize('Sulu is awesome'))->shouldBeCalled()->willReturn($node->reveal()); - - $structure = $this->prophesize(StructureInterface::class); - $structure->getStagedData()->willReturn(['pageTitle' => 'Sulu is awesome']); - $this->document->getStructure()->willReturn($structure->reveal()); - - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->hasNode()->willReturn(false); - $event->getParentNode()->willReturn($parentNode->reveal()); - $event->setNode($node->reveal())->shouldBeCalled(); - - $this->subscriber->setNodeOnPersist($event->reveal()); - } - - public function testSetNodeOnPersistWithProperty() - { - $property = $this->prophesize(PropertyMetadata::class); - $property->getName()->willReturn('pageTitle'); - - $this->metadata->hasPropertyWithTagName(ArticlePageSubscriber::PAGE_TITLE_TAG_NAME) - ->willReturn(false); - $this->metadata->hasProperty(ArticlePageSubscriber::PAGE_TITLE_PROPERTY_NAME) - ->willReturn(true); - $this->metadata->getProperty(ArticlePageSubscriber::PAGE_TITLE_PROPERTY_NAME) - ->willReturn($property->reveal()); - $node = $this->prophesize(NodeInterface::class); - - $parentNode = $this->prophesize(NodeInterface::class); - $parentNode->addNode(Urlizer::urlize('Sulu is awesome'))->shouldBeCalled()->willReturn($node->reveal()); - - $structure = $this->prophesize(StructureInterface::class); - $structure->getStagedData()->willReturn(['pageTitle' => 'Sulu is awesome']); - $this->document->getStructure()->willReturn($structure->reveal()); - - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->hasNode()->willReturn(false); - $event->getParentNode()->willReturn($parentNode->reveal()); - $event->setNode($node->reveal())->shouldBeCalled(); - - $this->subscriber->setNodeOnPersist($event->reveal()); - } - - public function testSetPageTitleOnPersist() - { - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - - $this->document->setPageTitle(null)->shouldBeCalled(); - - $this->subscriber->setPageTitleOnPersist($event->reveal()); - } - - public function testSetPageTitleOnPersistWithTag() - { - $property = $this->prophesize(PropertyMetadata::class); - $property->getName()->willReturn('pageTitle'); - - $this->metadata->hasPropertyWithTagName(ArticlePageSubscriber::PAGE_TITLE_TAG_NAME) - ->willReturn(true); - $this->metadata->getPropertyByTagName(ArticlePageSubscriber::PAGE_TITLE_TAG_NAME) - ->willReturn($property->reveal()); - - $structure = $this->prophesize(StructureInterface::class); - $structure->getStagedData()->willReturn(['pageTitle' => 'Sulu is awesome']); - $this->document->getStructure()->willReturn($structure->reveal()); - - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - - $this->document->setPageTitle('Sulu is awesome')->shouldBeCalled(); - - $this->subscriber->setPageTitleOnPersist($event->reveal()); - } - - public function testSetPageTitleOnPersistWithProperty() - { - $property = $this->prophesize(PropertyMetadata::class); - $property->getName()->willReturn('pageTitle'); - - $this->metadata->hasPropertyWithTagName(ArticlePageSubscriber::PAGE_TITLE_TAG_NAME) - ->willReturn(false); - $this->metadata->hasProperty(ArticlePageSubscriber::PAGE_TITLE_PROPERTY_NAME) - ->willReturn(true); - $this->metadata->getProperty(ArticlePageSubscriber::PAGE_TITLE_PROPERTY_NAME) - ->willReturn($property->reveal()); - - $structure = $this->prophesize(StructureInterface::class); - $structure->getStagedData()->willReturn(['pageTitle' => 'Sulu is awesome']); - $this->document->getStructure()->willReturn($structure->reveal()); - - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - - $this->document->setPageTitle('Sulu is awesome')->shouldBeCalled(); - - $this->subscriber->setPageTitleOnPersist($event->reveal()); - } -} diff --git a/Tests/Unit/Document/Subscriber/ArticleSubscriberTest.php b/Tests/Unit/Document/Subscriber/ArticleSubscriberTest.php deleted file mode 100644 index 5c96e1726..000000000 --- a/Tests/Unit/Document/Subscriber/ArticleSubscriberTest.php +++ /dev/null @@ -1,746 +0,0 @@ -indexer = $this->prophesize(IndexerInterface::class); - $this->liveIndexer = $this->prophesize(IndexerInterface::class); - $this->documentManager = $this->prophesize(DocumentManagerInterface::class); - $this->documentInspector = $this->prophesize(DocumentInspector::class); - $this->propertyEncoder = $this->prophesize(PropertyEncoder::class); - - $this->document = $this->prophesize(ArticleDocument::class); - $this->document->getUuid()->willReturn($this->uuid); - $this->document->getLocale()->willReturn($this->locale); - $this->documentManager->find($this->uuid, $this->locale)->willReturn($this->document->reveal()); - - $this->articleSubscriber = new ArticleSubscriber( - $this->indexer->reveal(), - $this->liveIndexer->reveal(), - $this->documentManager->reveal(), - $this->documentInspector->reveal(), - $this->propertyEncoder->reveal() - ); - } - - protected function prophesizeEvent($className, $locale = null, $options = null) - { - $event = $this->prophesize($className); - $event->getDocument()->willReturn($this->document->reveal()); - - if (null !== $options) { - $event->getOptions()->willReturn($options); - } - - if (null !== $locale) { - $event->getLocale()->willReturn($locale); - } - - return $event->reveal(); - } - - public function testHandleScheduleIndex() - { - $event = $this->prophesizeEvent(AbstractMappingEvent::class); - $this->articleSubscriber->handleScheduleIndex($event); - - $this->indexer->index(Argument::any())->shouldNotBeCalled(); - $this->indexer->flush()->shouldNotBeCalled(); - $this->liveIndexer->index(Argument::any())->shouldNotBeCalled(); - $this->liveIndexer->flush()->shouldNotBeCalled(); - } - - public function testHandleScheduleIndexLive() - { - $event = $this->prophesizeEvent(AbstractMappingEvent::class); - $this->articleSubscriber->handleScheduleIndexLive($event); - - $this->indexer->index(Argument::any())->shouldNotBeCalled(); - $this->indexer->flush()->shouldNotBeCalled(); - $this->liveIndexer->index(Argument::any())->shouldNotBeCalled(); - $this->liveIndexer->flush()->shouldNotBeCalled(); - } - - public function testHandleFlush() - { - $event = $this->prophesizeEvent(AbstractMappingEvent::class); - $this->articleSubscriber->handleScheduleIndex($event); - - $this->documentManager->find($this->uuid, $this->locale)->willReturn($this->document->reveal()); - $this->documentManager->refresh($this->document->reveal())->willReturn($this->document->reveal()); - - $this->articleSubscriber->handleFlush($this->prophesize(FlushEvent::class)->reveal()); - - $this->indexer->index($this->document->reveal())->shouldBeCalled(); - $this->indexer->flush()->shouldBeCalled(); - $this->liveIndexer->index(Argument::any())->shouldNotBeCalled(); - $this->liveIndexer->flush()->shouldNotBeCalled(); - } - - public function testHandleFlushLive() - { - $event = $this->prophesizeEvent(AbstractMappingEvent::class); - $this->articleSubscriber->handleScheduleIndexLive($event); - - $this->documentManager->find($this->uuid, $this->locale)->willReturn($this->document->reveal()); - $this->documentManager->refresh($this->document->reveal())->willReturn($this->document->reveal()); - - $this->articleSubscriber->handleFlushLive($this->prophesize(FlushEvent::class)->reveal()); - - $this->indexer->index(Argument::any())->shouldNotBeCalled(); - $this->indexer->flush()->shouldNotBeCalled(); - $this->liveIndexer->index($this->document->reveal())->shouldBeCalled(); - $this->liveIndexer->flush()->shouldBeCalled(); - } - - public function testHandleRemove() - { - $this->articleSubscriber->handleRemove($this->prophesizeEvent(RemoveEvent::class)); - - $this->indexer->remove($this->document->reveal())->shouldBeCalled(); - $this->indexer->flush()->shouldBeCalled(); - $this->liveIndexer->index(Argument::any())->shouldNotBeCalled(); - $this->liveIndexer->flush()->shouldNotBeCalled(); - } - - public function testHandleRemoveLive() - { - $this->articleSubscriber->handleRemoveLive($this->prophesizeEvent(RemoveEvent::class)); - - $this->indexer->remove(Argument::any())->shouldNotBeCalled(); - $this->indexer->flush()->shouldNotBeCalled(); - $this->liveIndexer->remove($this->document->reveal())->shouldBeCalled(); - $this->liveIndexer->flush()->shouldBeCalled(); - } - - public function testPublishChildren() - { - $children = [ - $this->prophesize(ArticlePageDocument::class)->reveal(), - $this->prophesize(ArticlePageDocument::class)->reveal(), - $this->prophesize(ArticlePageDocument::class)->reveal(), - ]; - - $this->document->getChildren()->willReturn(new \ArrayIterator($children)); - - foreach ($children as $child) { - $this->documentInspector->getLocalizationState($child)->willReturn(LocalizationState::LOCALIZED); - $this->documentManager->publish($child, $this->locale)->shouldBeCalled(); - } - - $this->articleSubscriber->publishChildren($this->prophesizeEvent(PublishEvent::class, $this->locale)); - } - - public function testSynchronizeChildren() - { - $document = $this->prophesize(ArticleDocument::class); - $liveNode = $this->prophesize(NodeInterface::class); - $draftNode = $this->prophesize(NodeInterface::class); - - $event = $this->prophesize(PublishEvent::class); - $event->getDocument()->willReturn($document->reveal()); - $event->getNode()->willReturn($liveNode->reveal()); - - $this->documentInspector->getNode($document->reveal())->willReturn($draftNode->reveal()); - - $children = [ - $this->createNodeMock('123-123-123'), - $this->createNodeMock('456-456-456'), - ]; - - $liveNode->getNodes()->willReturn($children); - $draftNode->getNodes()->willReturn($children); - - $this->articleSubscriber->synchronizeChildren($event->reveal()); - } - - public function testSynchronizeChildrenDifferenceRemove() - { - $document = $this->prophesize(ArticleDocument::class); - $liveNode = $this->prophesize(NodeInterface::class); - $draftNode = $this->prophesize(NodeInterface::class); - - $event = $this->prophesize(PublishEvent::class); - $event->getDocument()->willReturn($document->reveal()); - $event->getNode()->willReturn($liveNode->reveal()); - - $this->documentInspector->getNode($document->reveal())->willReturn($draftNode->reveal()); - - $children = [ - $this->createNodeMock('123-123-123'), - $this->createNodeMock('456-456-456', true), - ]; - - $liveNode->getNodes()->willReturn($children); - $draftNode->getNodes()->willReturn([$children[0]]); - - $this->articleSubscriber->synchronizeChildren($event->reveal()); - } - - public function testSynchronizeChildrenDifferenceAdd() - { - $document = $this->prophesize(ArticleDocument::class); - $liveNode = $this->prophesize(NodeInterface::class); - $draftNode = $this->prophesize(NodeInterface::class); - - $event = $this->prophesize(PublishEvent::class); - $event->getDocument()->willReturn($document->reveal()); - $event->getNode()->willReturn($liveNode->reveal()); - - $this->documentInspector->getNode($document->reveal())->willReturn($draftNode->reveal()); - - $children = [ - $this->createNodeMock('123-123-123'), - $this->createNodeMock('456-456-456'), - ]; - - $liveNode->getNodes()->willReturn([$children[0]]); - $draftNode->getNodes()->willReturn($children); - - // nothing should happen because publish new children will be done somewhere else - - $this->articleSubscriber->synchronizeChildren($event->reveal()); - } - - public function testSynchronizeChildrenDifferenceAddAndRemove() - { - $document = $this->prophesize(ArticleDocument::class); - $liveNode = $this->prophesize(NodeInterface::class); - $draftNode = $this->prophesize(NodeInterface::class); - - $event = $this->prophesize(PublishEvent::class); - $event->getDocument()->willReturn($document->reveal()); - $event->getNode()->willReturn($liveNode->reveal()); - - $this->documentInspector->getNode($document->reveal())->willReturn($draftNode->reveal()); - - $children = [ - $this->createNodeMock('123-123-123', true), - $this->createNodeMock('456-456-456'), - ]; - - $liveNode->getNodes()->willReturn([$children[0]]); - $draftNode->getNodes()->willReturn([$children[1]]); - - $this->articleSubscriber->synchronizeChildren($event->reveal()); - } - - private function createNodeMock($uuid, $removeCall = false) - { - $node = $this->prophesize(NodeInterface::class); - $node->getIdentifier()->willReturn($uuid); - - if ($removeCall) { - $node->remove()->shouldBeCalled(); - } else { - $node->remove()->shouldNotBeCalled(); - } - - return $node->reveal(); - } - - public function testRemoveDraftChildren() - { - $children = [ - $this->prophesize(ArticlePageDocument::class)->reveal(), - $this->prophesize(ArticlePageDocument::class)->reveal(), - $this->prophesize(ArticlePageDocument::class)->reveal(), - ]; - - $this->document->getChildren()->willReturn($children); - - foreach ($children as $child) { - $this->documentInspector->getLocalizationState($child)->willReturn(LocalizationState::LOCALIZED); - $this->documentManager->removeDraft($child, $this->locale)->shouldBeCalled(); - } - - $this->articleSubscriber->removeDraftChildren($this->prophesizeEvent(RemoveDraftEvent::class, $this->locale)); - } - - public function testRemoveDraftChildrenNotExists() - { - $child = $this->prophesize(ArticlePageDocument::class)->reveal(); - - $this->document->getChildren()->willReturn([$child]); - - $this->documentInspector->getLocalizationState($child)->willReturn(LocalizationState::LOCALIZED); - $this->documentManager->removeDraft($child, $this->locale)->shouldBeCalled() - ->willThrow(new PathNotFoundException()); - - $node = $this->prophesize(NodeInterface::class); - $node->remove()->shouldBeCalled(); - $this->documentInspector->getNode($child)->willReturn($node->reveal()); - - $this->articleSubscriber->removeDraftChildren($this->prophesizeEvent(RemoveDraftEvent::class, $this->locale)); - } - - public function testHandleChildrenPersistWithoutChanges() - { - $children = []; - - for ($id = 1; $id < 4; ++$id) { - $child = $this->prophesize(ArticlePageDocument::class); - $child->getUuid()->willReturn($id); - $child->getLocale()->willReturn($this->locale); - $child->getShadowLocale()->willReturn(null); - $child->isShadowLocaleEnabled()->willReturn(false); - $child->getStructureType()->willReturn('my-other-test'); - $child->setStructureType('my-test')->shouldBeCalled(); - - $this->documentInspector->getLocalizationState($child)->willReturn(LocalizationState::LOCALIZED); - - $this->documentManager->persist( - $child->reveal(), - $this->locale, - [ - 'clear_missing_content' => false, - 'auto_name' => false, - 'auto_rename' => false, - ] - )->shouldBeCalled(); - - $children[] = $child; - } - - $this->document->getStructureType()->willReturn('my-test'); - $this->document->getChildren()->willReturn($children); - $this->document->getShadowLocale()->willReturn(null); - $this->document->isShadowLocaleEnabled()->willReturn(false); - - $this->articleSubscriber->handleChildrenPersist( - $this->prophesizeEvent(PersistEvent::class, $this->locale, []) - ); - } - - public function testHandleChildrenPersistWithStructureTypeChange() - { - $children = []; - - for ($id = 1; $id < 4; ++$id) { - /** @var ArticlePageDocument $child */ - $child = $this->prophesize(ArticlePageDocument::class); - $child->getUuid()->willReturn($id); - $child->getLocale()->willReturn($this->locale); - $child->getShadowLocale()->willReturn(null); - $child->isShadowLocaleEnabled()->willReturn(false); - $child->getStructureType()->willReturn('old'); - $child->setStructureType('changed-structure')->shouldBeCalled(); - - $this->documentInspector->getLocalizationState($child)->willReturn(LocalizationState::LOCALIZED); - - $this->documentManager->persist( - $child, - $this->locale, - [ - 'clear_missing_content' => false, - 'auto_name' => false, - 'auto_rename' => false, - ] - )->shouldBeCalled(); - - $children[] = $child; - } - - $this->document->getStructureType()->willReturn('changed-structure'); - $this->document->getChildren()->willReturn($children); - $this->document->getShadowLocale()->willReturn(null); - $this->document->isShadowLocaleEnabled()->willReturn(false); - - $this->articleSubscriber->handleChildrenPersist( - $this->prophesizeEvent(PersistEvent::class, $this->locale, []) - ); - } - - public function testHandleChildrenPersistShadow() - { - $children = []; - - for ($id = 1; $id < 4; ++$id) { - /** @var ArticlePageDocument $child */ - $child = $this->prophesize(ArticlePageDocument::class); - $child->getUuid()->willReturn($id); - $child->getLocale()->willReturn($this->locale); - $child->getShadowLocale()->willReturn(null); - $child->isShadowLocaleEnabled()->willReturn(false); - $child->getStructureType()->willReturn('nice_structure'); - $child->setShadowLocaleEnabled(true)->shouldBeCalled(); - $child->setShadowLocale('de')->shouldBeCalled(); - - $this->documentInspector->getLocalizationState($child)->willReturn(LocalizationState::LOCALIZED); - - $this->documentManager->persist( - $child, - $this->locale, - [ - 'clear_missing_content' => false, - 'auto_name' => false, - 'auto_rename' => false, - ] - )->shouldBeCalled(); - - $children[] = $child; - } - - $this->document->getStructureType()->willReturn('nice_structure'); - $this->document->getChildren()->willReturn($children); - $this->document->getShadowLocale()->willReturn('de'); - $this->document->isShadowLocaleEnabled()->willReturn(true); - - $this->articleSubscriber->handleChildrenPersist( - $this->prophesizeEvent(PersistEvent::class, $this->locale, []) - ); - } - - public function testHydratePageData() - { - $node = $this->prophesize(NodeInterface::class); - - $event = $this->prophesize(HydrateEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getNode()->willReturn($node->reveal()); - - $this->documentInspector->getLocalizationState( - $this->document->reveal() - )->willReturn(LocalizationState::LOCALIZED); - - $propertyName = 'i18n:' . $this->locale . '-' . ArticleSubscriber::PAGES_PROPERTY; - $this->propertyEncoder->localizedSystemName(ArticleSubscriber::PAGES_PROPERTY, $this->locale) - ->willReturn($propertyName); - - $node->getPropertyValueWithDefault($propertyName, \json_encode([])) - ->willReturn(\json_encode([['title' => 'Test title']])); - - $this->document->setPages([['title' => 'Test title']])->shouldBeCalled(); - $this->document->getOriginalLocale()->willReturn($this->locale); - - $this->articleSubscriber->hydratePageData($event->reveal()); - } - - public function testHydratePageDataShadow() - { - $node = $this->prophesize(NodeInterface::class); - - $event = $this->prophesize(HydrateEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getNode()->willReturn($node->reveal()); - - $this->documentInspector->getLocalizationState( - $this->document->reveal() - )->willReturn(LocalizationState::SHADOW); - - $propertyNameEN = 'i18n:en-' . ArticleSubscriber::PAGES_PROPERTY; - $this->propertyEncoder->localizedSystemName(ArticleSubscriber::PAGES_PROPERTY, 'en') - ->willReturn($propertyNameEN); - - $propertyNameDE = 'i18n:' . $this->locale . '-' . ArticleSubscriber::PAGES_PROPERTY; - $this->propertyEncoder->localizedSystemName(ArticleSubscriber::PAGES_PROPERTY, $this->locale) - ->willReturn($propertyNameDE); - - $node->getPropertyValueWithDefault($propertyNameDE, \json_encode([])) - ->willReturn(\json_encode( - [ - [ - 'title' => 'Test Ãœberschrift', - 'routePath' => '/test-ueberschrift', - ], - ] - )); - - $node->getPropertyValueWithDefault($propertyNameEN, \json_encode([])) - ->willReturn(\json_encode( - [ - [ - 'title' => 'Test Headline', - 'routePath' => '/test-headline', - ], - ] - )); - - $this->document->getLocale()->willReturn($this->locale); - $this->document->getOriginalLocale()->willReturn('en'); - - $this->document->setPages( - [ - [ - 'title' => 'Test Ãœberschrift', - 'routePath' => '/test-headline', - ], - ] - )->shouldBeCalled(); - - $this->articleSubscriber->hydratePageData($event->reveal()); - } - - public function testPersistPageData() - { - $node = $this->prophesize(NodeInterface::class); - - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getNode()->willReturn($node->reveal()); - $event->getLocale()->willReturn($this->locale); - - $pages = [ - [ - 'uuid' => '123-123-123', - 'title' => 'Test article: page 1', - 'routePath' => '/test-article', - 'pageNumber' => 1, - ], - [ - 'uuid' => '321-321-321', - 'title' => 'Test article: page 2', - 'routePath' => '/test-article/page-2', - 'pageNumber' => 2, - ], - ]; - - $this->document->getUuid()->willReturn($pages[0]['uuid']); - $this->document->getPageTitle()->willReturn($pages[0]['title']); - $this->document->getRoutePath()->willReturn($pages[0]['routePath']); - $this->document->getPageNumber()->willReturn($pages[0]['pageNumber']); - - $child = $this->prophesize(ArticlePageDocument::class); - $child->getUuid()->willReturn($pages[1]['uuid']); - $child->getPageTitle()->willReturn($pages[1]['title']); - $child->getRoutePath()->willReturn($pages[1]['routePath']); - $child->getPageNumber()->willReturn($pages[1]['pageNumber']); - $this->document->getChildren()->willReturn(new \ArrayIterator([$child->reveal()])); - - $this->documentInspector->getLocalizationState($child->reveal())->willReturn(LocalizationState::LOCALIZED); - - $propertyName = 'i18n:' . $this->locale . '-' . ArticleSubscriber::PAGES_PROPERTY; - $this->propertyEncoder->localizedSystemName(ArticleSubscriber::PAGES_PROPERTY, $this->locale) - ->willReturn($propertyName); - - $this->document->setPages($pages)->shouldBeCalled(); - $node->setProperty($propertyName, \json_encode($pages))->shouldBeCalled(); - - $this->articleSubscriber->persistPageData($event->reveal()); - } - - public function testPersistPageDataOnReorder() - { - $node = $this->prophesize(NodeInterface::class); - - $orderedDocument = $this->prophesize(ArticlePageDocument::class); - $orderedDocument->getParent()->willReturn($this->document->reveal()); - $this->document->getLocale()->willReturn($this->locale); - $this->documentInspector->getNode($this->document->reveal())->willReturn($node->reveal()); - - $event = $this->prophesize(ReorderEvent::class); - $event->getDocument()->willReturn($orderedDocument->reveal()); - - $pages = [ - [ - 'uuid' => '123-123-123', - 'title' => 'Test article: page 1', - 'routePath' => '/test-article', - 'pageNumber' => 1, - ], - [ - 'uuid' => '321-321-321', - 'title' => 'Test article: page 2', - 'routePath' => '/test-article/page-2', - 'pageNumber' => 2, - ], - ]; - - $this->document->getUuid()->willReturn($pages[0]['uuid']); - $this->document->getPageTitle()->willReturn($pages[0]['title']); - $this->document->getRoutePath()->willReturn($pages[0]['routePath']); - $this->document->getPageNumber()->willReturn($pages[0]['pageNumber']); - - $child = $this->prophesize(ArticlePageDocument::class); - $child->getUuid()->willReturn($pages[1]['uuid']); - $child->getPageTitle()->willReturn($pages[1]['title']); - $child->getRoutePath()->willReturn($pages[1]['routePath']); - $child->getPageNumber()->willReturn($pages[1]['pageNumber']); - $this->document->getChildren()->willReturn(new \ArrayIterator([$child->reveal()])); - - $this->documentInspector->getLocalizationState($child->reveal())->willReturn(LocalizationState::LOCALIZED); - $this->documentInspector->getLocale($this->document->reveal())->willReturn('de'); - - $propertyName = 'i18n:' . $this->locale . '-' . ArticleSubscriber::PAGES_PROPERTY; - $this->propertyEncoder->localizedSystemName(ArticleSubscriber::PAGES_PROPERTY, $this->locale)->willReturn( - $propertyName - ); - - $this->document->setPages($pages)->shouldBeCalled(); - $node->setProperty($propertyName, \json_encode($pages))->shouldBeCalled(); - $this->document->setWorkflowStage(WorkflowStage::TEST)->shouldBeCalled(); - $this->document->setWorkflowStage(WorkflowStage::TEST); - - $this->documentManager->persist($this->document->reveal(), 'de')->shouldBeCalled(); - - $this->articleSubscriber->persistPageDataOnReorder($event->reveal()); - } - - public function testHandleRemoveLocaleWithInvalidDocument() - { - $event = $this->prophesize(RemoveLocaleEvent::class); - $document = $this->prophesize(\stdClass::class); // Not an ArticleDocument - $event->getDocument()->willReturn($document->reveal()); - - // Ensure the indexer methods are not called - $this->indexer->replaceWithGhostData()->shouldNotBeCalled(); - $this->indexer->flush()->shouldNotBeCalled(); - - // Call the method and make sure it doesn't throw exceptions - $this->articleSubscriber->handleRemoveLocale($event->reveal()); - } - - public function testHandleRemoveLocale() - { - $event = $this->prophesize(RemoveLocaleEvent::class); - $document = $this->prophesize(ArticleDocument::class); - $document->getOriginalLocale()->willReturn('en'); - $document->getUuid()->willReturn($this->uuid); - $event->getDocument()->willReturn($document->reveal()); - $event->getLocale()->willReturn('de'); - - $this->documentInspector->getConcreteLocales($document->reveal())->willReturn(['en', 'fr']); - - $originalDocument = $this->prophesize(ArticleDocument::class); - $this->documentManager->find($this->uuid, 'en')->willReturn($originalDocument->reveal()); - - // Ensure the indexer methods are called - $this->indexer->replaceWithGhostData($originalDocument->reveal(), 'de')->shouldBeCalled(); - $this->indexer->flush()->shouldBeCalled(); - - // Call the method - $this->articleSubscriber->handleRemoveLocale($event->reveal()); - } - - public function testHandleRemoveLocaleWithDefaultLocaleDoesNotExists() - { - $event = $this->prophesize(RemoveLocaleEvent::class); - $document = $this->prophesize(ArticleDocument::class); - $document->getOriginalLocale()->willReturn('en'); - $document->getUuid()->willReturn($this->uuid); - $event->getDocument()->willReturn($document->reveal()); - $event->getLocale()->willReturn('de'); - - $this->documentInspector->getConcreteLocales($document->reveal())->willReturn(['fr']); - - $originalDocument = $this->prophesize(ArticleDocument::class); - $this->documentManager->find($this->uuid, 'fr')->willReturn($originalDocument->reveal()); - - // Ensure the indexer methods are called - $this->indexer->replaceWithGhostData($originalDocument->reveal(), 'de')->shouldBeCalled(); - $this->indexer->flush()->shouldBeCalled(); - - // Call the method - $this->articleSubscriber->handleRemoveLocale($event->reveal()); - } - - public function testHandleRemoveLocaleLiveWithInvalidDocument() - { - $event = $this->prophesize(RemoveLocaleEvent::class); - $document = $this->prophesize(\stdClass::class); // Not an ArticleDocument - $event->getDocument()->willReturn($document->reveal()); - - // Ensure the liveIndexer methods are not called - $this->liveIndexer->remove()->shouldNotBeCalled(); - $this->liveIndexer->flush()->shouldNotBeCalled(); - - // Call the method and make sure it doesn't throw exceptions - $this->articleSubscriber->handleRemoveLocaleLive($event->reveal()); - } - - public function testHandleRemoveLocaleLive() - { - // Create a mock RemoveLocaleEvent with an ArticleDocument - $event = $this->prophesize(RemoveLocaleEvent::class); - $document = $this->prophesize(ArticleDocument::class); - $event->getDocument()->willReturn($document->reveal()); - $event->getLocale()->willReturn('en'); - - // Ensure the liveIndexer methods are called - $this->liveIndexer->remove($document->reveal(), 'en')->shouldBeCalled(); - $this->liveIndexer->flush()->shouldBeCalled(); - - // Call the method - $this->articleSubscriber->handleRemoveLocaleLive($event->reveal()); - } -} diff --git a/Tests/Unit/Document/Subscriber/PageSubscriberTest.php b/Tests/Unit/Document/Subscriber/PageSubscriberTest.php deleted file mode 100644 index fc797da1d..000000000 --- a/Tests/Unit/Document/Subscriber/PageSubscriberTest.php +++ /dev/null @@ -1,228 +0,0 @@ -documentInspector = $this->prophesize(DocumentInspector::class); - $this->propertyEncoder = $this->prophesize(PropertyEncoder::class); - $this->documentManager = $this->prophesize(DocumentManagerInterface::class); - - $this->document = $this->prophesize(PageBehavior::class); - $this->node = $this->prophesize(NodeInterface::class); - - $this->pageSubscriber = new PageSubscriber( - $this->documentInspector->reveal(), $this->propertyEncoder->reveal(), $this->documentManager->reveal() - ); - } - - public function testHandlePersist() - { - $child1 = $this->prophesize(\stdClass::class); - $child2 = $this->prophesize(PageBehavior::class); - $child2->getUuid()->willReturn('1-1-1'); - $child3 = $this->prophesize(PageBehavior::class); - $child3->getUuid()->willReturn('1-2-2'); - - $event = $this->prophesize(PersistEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getNode()->willReturn($this->node->reveal()); - - $this->node->hasProperty('sulu:pageNumber')->willReturn(false); - - $parentDocument = $this->prophesize(ChildrenBehavior::class); - $parentDocument->getChildren()->willReturn( - [ - $child1->reveal(), - $child2->reveal(), - $child3->reveal(), - ] - ); - $this->document->getParent()->willReturn($parentDocument->reveal()); - $this->document->getUuid()->willReturn('1-2-3'); - $this->document->getPageNumber()->willReturn(null); - $this->document->setPageNumber(3)->shouldBeCalled(); - - $this->propertyEncoder->systemName(PageSubscriber::FIELD)->willReturn('sulu:' . PageSubscriber::FIELD); - - $this->node->setProperty('sulu:' . PageSubscriber::FIELD, 3)->shouldBeCalled(); - - $this->pageSubscriber->handlePersist($event->reveal()); - } - - public function testHandleRemove() - { - $child1 = $this->prophesize(\stdClass::class); - $child2 = $this->prophesize(PageBehavior::class); - $child2->getUuid()->willReturn('1-1-1'); - $child3 = $this->prophesize(PageBehavior::class); - $child3->getUuid()->willReturn('1-2-2'); - - $childNode2 = $this->prophesize(NodeInterface::class); - $this->documentInspector->getNode($child2->reveal())->willReturn($childNode2->reveal()); - $childNode3 = $this->prophesize(NodeInterface::class); - $this->documentInspector->getNode($child3->reveal())->willReturn($childNode3->reveal()); - - $event = $this->prophesize(RemoveEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - - $parentDocument = $this->prophesize(ChildrenBehavior::class); - $parentDocument->getChildren()->willReturn( - [ - $child1->reveal(), - $child2->reveal(), - $this->document->reveal(), - $child3->reveal(), - ] - ); - $this->document->getParent()->willReturn($parentDocument->reveal()); - $this->document->getUuid()->willReturn('1-2-3'); - - $this->propertyEncoder->systemName(PageSubscriber::FIELD)->willReturn('sulu:' . PageSubscriber::FIELD); - - $childNode2->setProperty('sulu:' . PageSubscriber::FIELD, 2)->shouldBeCalled(); - $childNode3->setProperty('sulu:' . PageSubscriber::FIELD, 3)->shouldBeCalled(); - - $this->pageSubscriber->handleRemove($event->reveal()); - } - - public function testHandlePublishPageNumber() - { - $event = $this->prophesize(PublishEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getNode()->willReturn($this->node->reveal()); - - $this->propertyEncoder->systemName(PageSubscriber::FIELD)->willReturn('sulu:' . PageSubscriber::FIELD); - - $this->document->getPageNumber()->willReturn(1); - $this->node->setProperty('sulu:' . PageSubscriber::FIELD, 1)->shouldBeCalled(); - - $this->pageSubscriber->handlePublishPageNumber($event->reveal()); - } - - public function testHandleRestore() - { - $event = $this->prophesize(RestoreEvent::class); - - $parentDocument = $this->prophesize(ChildrenBehavior::class); - $parentDocument->getChildren()->willReturn([$this->document->reveal()]); - - $event->getDocument()->willReturn($parentDocument->reveal()); - $this->documentInspector->getNode($this->document->reveal())->willReturn($this->node->reveal()); - - $this->propertyEncoder->systemName(PageSubscriber::FIELD)->willReturn('sulu:' . PageSubscriber::FIELD); - - $this->document->getPageNumber()->willReturn(2); - $this->node->setProperty('sulu:' . PageSubscriber::FIELD, 2)->shouldBeCalled(); - - $this->pageSubscriber->handleRestore($event->reveal()); - } - - public function testHandleReorder() - { - $parentDocument = $this->prophesize(ChildrenBehavior::class); - $this->document->getParent()->willReturn($parentDocument->reveal()); - - $nodes = [ - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - ]; - - $nodes[0]->getIdentifier()->willReturn('1-1-1'); - $nodes[1]->getIdentifier()->willReturn('1-2-2'); - $nodes[2]->getIdentifier()->willReturn('1-2-3'); - - $parentNode = $this->prophesize(NodeInterface::class); - $parentNode->getNodes()->willReturn( - \array_map( - function($item) { - return $item->reveal(); - }, - $nodes - ) - ); - - $this->documentInspector->getNode($parentDocument->reveal())->willReturn($parentNode->reveal()); - - $documents = [ - $this->prophesize(PageBehavior::class), - $this->prophesize(PageBehavior::class), - $this->prophesize(PageBehavior::class), - ]; - - $this->documentManager->find('1-1-1', 'de')->willReturn($documents[0]->reveal()); - $this->documentManager->find('1-2-2', 'de')->willReturn($documents[1]->reveal()); - $this->documentManager->find('1-2-3', 'de')->willReturn($documents[2]->reveal()); - - $event = $this->prophesize(ReorderEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getLocale()->willReturn('de'); - - $this->propertyEncoder->systemName(PageSubscriber::FIELD)->willReturn('sulu:' . PageSubscriber::FIELD); - - $documents[0]->setPageNumber(2)->shouldBeCalled(); - $nodes[0]->setProperty('sulu:' . PageSubscriber::FIELD, 2)->shouldBeCalled(); - $documents[1]->setPageNumber(3)->shouldBeCalled(); - $nodes[1]->setProperty('sulu:' . PageSubscriber::FIELD, 3)->shouldBeCalled(); - $documents[2]->setPageNumber(4)->shouldBeCalled(); - $nodes[2]->setProperty('sulu:' . PageSubscriber::FIELD, 4)->shouldBeCalled(); - - $this->pageSubscriber->handleReorder($event->reveal()); - } -} diff --git a/Tests/Unit/Document/Subscriber/RoutableSubscriberTest.php b/Tests/Unit/Document/Subscriber/RoutableSubscriberTest.php deleted file mode 100644 index df560e3ea..000000000 --- a/Tests/Unit/Document/Subscriber/RoutableSubscriberTest.php +++ /dev/null @@ -1,417 +0,0 @@ -chainGenerator = $this->prophesize(ChainRouteGeneratorInterface::class); - $this->routeManager = $this->prophesize(RouteManagerInterface::class); - $this->routeRepository = $this->prophesize(RouteRepositoryInterface::class); - $this->entityManager = $this->prophesize(EntityManagerInterface::class); - $this->documentManager = $this->prophesize(DocumentManagerInterface::class); - $this->documentInspector = $this->prophesize(DocumentInspector::class); - $this->propertyEncoder = $this->prophesize(PropertyEncoder::class); - $this->metadataFactory = $this->prophesize(StructureMetadataFactoryInterface::class); - $this->documentInspector = $this->prophesize(DocumentInspector::class); - $this->documentManager = $this->prophesize(DocumentManagerInterface::class); - $this->conflictResolver = $this->prophesize(ConflictResolverInterface::class); - - $this->document = $this->prophesize(RoutableBehavior::class); - - $this->node = $this->prophesize(NodeInterface::class); - $this->node->getIdentifier()->willReturn('123-123-123'); - - $this->conflictResolver->resolve(Argument::type(RouteInterface::class))->will( - function(array $arguments) { - return $arguments[0]; - } - ); - - $this->routableSubscriber = new RoutableSubscriber( - $this->chainGenerator->reveal(), - $this->routeManager->reveal(), - $this->routeRepository->reveal(), - $this->entityManager->reveal(), - $this->documentManager->reveal(), - $this->documentInspector->reveal(), - $this->propertyEncoder->reveal(), - $this->metadataFactory->reveal(), - $this->conflictResolver->reveal() - ); - } - - protected function prophesizeEvent($className) - { - $event = $this->prophesize($className); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getLocale()->willReturn('de'); - $event->getNode()->willReturn($this->node->reveal()); - - return $event->reveal(); - } - - public function testHandlePersist() - { - $document = $this->prophesize(RoutableBehavior::class); - $document->willImplement(ChildrenBehavior::class); - - $event = $this->prophesize(AbstractMappingEvent::class); - $event->getDocument()->willReturn($document->reveal()); - - $metadata = $this->prophesize(StructureMetadata::class); - $metadata->hasTag(Argument::any())->willReturn(false); - - $this->metadataFactory->getStructureMetadata('article', 'default')->willReturn($metadata->reveal()); - $this->propertyEncoder->localizedSystemName('routePath', 'de')->willReturn('i18n:de-routePath'); - $this->propertyEncoder->localizedContentName('routePathName', 'de')->willReturn('i18n:de-routePathName'); - - $children = [ - $this->prophesize(RoutablePageBehavior::class), - $this->prophesize(RoutablePageBehavior::class), - $this->prophesize(RoutablePageBehavior::class), - ]; - - foreach ($children as $child) { - $child->getStructureType()->willReturn('default'); - $this->documentInspector->getLocale($child->reveal())->willReturn('de'); - } - - $document->getChildren() - ->willReturn([$children[0]->reveal(), $children[1]->reveal(), $children[2]->reveal()]); - - $nodes = [ - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - ]; - $this->documentInspector->getNode($children[0]->reveal())->willReturn($nodes[0]->reveal()); - $this->documentInspector->getNode($children[1]->reveal())->willReturn($nodes[1]->reveal()); - $this->documentInspector->getNode($children[2]->reveal())->willReturn($nodes[2]->reveal()); - - $routes = [ - $this->prophesize(RouteInterface::class), - $this->prophesize(RouteInterface::class), - $this->prophesize(RouteInterface::class), - ]; - $routes[0]->getPath()->willReturn('/test-1'); - $routes[1]->getPath()->willReturn('/test-2'); - $routes[2]->getPath()->willReturn('/test-3'); - $this->chainGenerator->generate($children[0]->reveal())->willReturn($routes[0]->reveal()); - $this->chainGenerator->generate($children[1]->reveal())->willReturn($routes[1]->reveal()); - $this->chainGenerator->generate($children[2]->reveal())->willReturn($routes[2]->reveal()); - - $children[0]->setRoutePath('/test-1')->shouldBeCalled(); - $children[1]->setRoutePath('/test-2')->shouldBeCalled(); - $children[2]->setRoutePath('/test-3')->shouldBeCalled(); - - $nodes[0]->setProperty('i18n:de-routePath', '/test-1')->shouldBeCalled(); - $nodes[0]->setProperty('i18n:de-routePathName', 'i18n:de-routePath')->shouldBeCalled(); - $nodes[1]->setProperty('i18n:de-routePath', '/test-2')->shouldBeCalled(); - $nodes[1]->setProperty('i18n:de-routePathName', 'i18n:de-routePath')->shouldBeCalled(); - $nodes[2]->setProperty('i18n:de-routePath', '/test-3')->shouldBeCalled(); - $nodes[2]->setProperty('i18n:de-routePathName', 'i18n:de-routePath')->shouldBeCalled(); - - $this->routableSubscriber->handlePersist($event->reveal()); - } - - public function testHandleRemove() - { - $this->document->willImplement(ChildrenBehavior::class); - - $this->documentInspector->getLocales($this->document->reveal())->willReturn(['de', 'en']); - - $event = $this->prophesize(RemoveEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - - $child2 = $this->prophesize(RoutableBehavior::class); - $child2->getRoutePath()->willReturn('/test/test-2'); - - $child1 = $this->prophesize(RoutableBehavior::class); - $child1->willImplement(ChildrenBehavior::class); - $child1->getChildren()->willReturn([$child2->reveal()]); - $child1->getRoutePath()->willReturn('/test/test-1'); - - $this->document->getChildren()->willReturn([$child1->reveal()]); - - $route1de = $this->prophesize(RouteInterface::class); - $route1en = $this->prophesize(RouteInterface::class); - $route2de = $this->prophesize(RouteInterface::class); - $route2en = $this->prophesize(RouteInterface::class); - - $this->routeRepository->findByPath('/test/test-1', 'de')->willReturn($route1de->reveal()); - $this->routeRepository->findByPath('/test/test-1', 'en')->willReturn($route1en->reveal()); - $this->routeRepository->findByPath('/test/test-2', 'de')->willReturn($route2de->reveal()); - $this->routeRepository->findByPath('/test/test-2', 'en')->willReturn($route2en->reveal()); - - $this->entityManager->remove($route1de->reveal())->shouldBeCalled(); - $this->entityManager->remove($route1en->reveal())->shouldBeCalled(); - $this->entityManager->remove($route2de->reveal())->shouldBeCalled(); - $this->entityManager->remove($route2en->reveal())->shouldBeCalled(); - $this->entityManager->flush()->shouldBeCalled(); - - $this->routableSubscriber->handleRemove($event->reveal()); - } - - public function testHandleCopy() - { - $this->document->willImplement(ChildrenBehavior::class); - - $event = $this->prophesize(CopyEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - $event->getCopiedPath()->willReturn('/cmf/articles/2017/04/test-article'); - - $this->documentInspector->getLocales($this->document->reveal())->willReturn(['de']); - $this->documentManager->find('/cmf/articles/2017/04/test-article', 'de')->willReturn($this->document->reveal()); - - $route = $this->prophesize(RouteInterface::class); - $route->getPath()->willReturn('/test'); - - $this->chainGenerator->generate($this->document->reveal())->willReturn($route->reveal()); - - $this->document->getStructureType()->willReturn('default'); - $metadata = $this->prophesize(StructureMetadata::class); - $metadata->hasTag(RoutableSubscriber::TAG_NAME)->willReturn(false); - $this->metadataFactory->getStructureMetadata('article', 'default')->willReturn($metadata->reveal()); - - $this->propertyEncoder->localizedSystemName(RoutableSubscriber::ROUTE_FIELD, 'de') - ->willReturn('i18n:de-routePath'); - - $children = [ - $this->prophesize(RoutablePageBehavior::class), - $this->prophesize(RoutablePageBehavior::class), - $this->prophesize(RoutablePageBehavior::class), - ]; - - foreach ($children as $child) { - $child->getStructureType()->willReturn('default'); - $this->documentInspector->getLocale($child->reveal())->willReturn('de'); - } - - $children[0]->getRoutePath()->willReturn('/test-old-1'); - $children[1]->getRoutePath()->willReturn('/test-old-2'); - $children[2]->getRoutePath()->willReturn('/test-old-3'); - - $this->routeRepository->findByPath('/test-old-1', 'de')->willReturn(null); - $this->routeRepository->findByPath('/test-old-2', 'de')->willReturn(null); - $this->routeRepository->findByPath('/test-old-3', 'de')->willReturn(null); - - $children[0]->getRoute()->willReturn(null); - $children[1]->getRoute()->willReturn(null); - $children[2]->getRoute()->willReturn(null); - - $children[0]->getUuid()->willReturn('123-123-123'); - $children[1]->getUuid()->willReturn('231-231-231'); - $children[2]->getUuid()->willReturn('312-312-312'); - - $children[0]->getClass()->willReturn('Article'); - $children[1]->getClass()->willReturn('Article'); - $children[2]->getClass()->willReturn('Article'); - - $this->routeRepository->findByEntity('Article', '123-123-123', 'de')->willReturn(null); - $this->routeRepository->findByEntity('Article', '231-231-231', 'de')->willReturn(null); - $this->routeRepository->findByEntity('Article', '312-312-312', 'de')->willReturn(null); - - $this->document->getChildren() - ->willReturn([$children[0]->reveal(), $children[1]->reveal(), $children[2]->reveal()]); - - $nodes = [ - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - ]; - $this->documentInspector->getNode($children[0]->reveal())->willReturn($nodes[0]->reveal()); - $this->documentInspector->getNode($children[1]->reveal())->willReturn($nodes[1]->reveal()); - $this->documentInspector->getNode($children[2]->reveal())->willReturn($nodes[2]->reveal()); - - $routes = [ - $this->prophesize(RouteInterface::class), - $this->prophesize(RouteInterface::class), - $this->prophesize(RouteInterface::class), - ]; - - $routes[0]->getPath()->willReturn('/test-1'); - $routes[1]->getPath()->willReturn('/test-2'); - $routes[2]->getPath()->willReturn('/test-3'); - - $this->routeManager->create($children[0]->reveal())->willReturn($routes[0]->reveal()); - $this->routeManager->create($children[1]->reveal())->willReturn($routes[1]->reveal()); - $this->routeManager->create($children[2]->reveal())->willReturn($routes[2]->reveal()); - - $this->entityManager->persist($routes[0])->shouldBeCalled(); - $this->entityManager->persist($routes[1])->shouldBeCalled(); - $this->entityManager->persist($routes[2])->shouldBeCalled(); - - $children[0]->setRoutePath('/test-1')->shouldBeCalled(); - $children[1]->setRoutePath('/test-2')->shouldBeCalled(); - $children[2]->setRoutePath('/test-3')->shouldBeCalled(); - - $nodes[0]->setProperty('i18n:de-routePath', '/test-1')->shouldBeCalled(); - $nodes[1]->setProperty('i18n:de-routePath', '/test-2')->shouldBeCalled(); - $nodes[2]->setProperty('i18n:de-routePath', '/test-3')->shouldBeCalled(); - - $this->routableSubscriber->handleCopy($event->reveal()); - } - - public function testHandleReorder() - { - $this->document->willImplement(ParentBehavior::class); - - $event = $this->prophesize(ReorderEvent::class); - $event->getDocument()->willReturn($this->document->reveal()); - - $parentDocument = $this->prophesize(ChildrenBehavior::class); - $parentDocument->willImplement(StructureBehavior::class); - $this->document->getParent()->willReturn($parentDocument->reveal()); - - $metadata = $this->prophesize(StructureMetadata::class); - $metadata->hasTag(Argument::any())->willReturn(false); - - $this->metadataFactory->getStructureMetadata('article', 'default')->willReturn($metadata->reveal()); - $this->propertyEncoder->localizedSystemName('routePath', 'de')->willReturn('i18n:de-routePath'); - $this->propertyEncoder->localizedContentName('routePathName', 'de')->willReturn('i18n:de-routePathName'); - - $children = [ - $this->prophesize(RoutablePageBehavior::class), - $this->prophesize(RoutablePageBehavior::class), - $this->prophesize(RoutablePageBehavior::class), - ]; - - foreach ($children as $child) { - $child->getStructureType()->willReturn('default'); - $this->documentInspector->getLocale($child)->willReturn('de'); - } - - $parentDocument->getChildren() - ->willReturn([$children[0]->reveal(), $children[1]->reveal(), $children[2]->reveal()]); - - $nodes = [ - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - $this->prophesize(NodeInterface::class), - ]; - $this->documentInspector->getNode($children[0]->reveal())->willReturn($nodes[0]->reveal()); - $this->documentInspector->getNode($children[1]->reveal())->willReturn($nodes[1]->reveal()); - $this->documentInspector->getNode($children[2]->reveal())->willReturn($nodes[2]->reveal()); - - $routes = [ - $this->prophesize(RouteInterface::class), - $this->prophesize(RouteInterface::class), - $this->prophesize(RouteInterface::class), - ]; - $routes[0]->getPath()->willReturn('/test-1'); - $routes[1]->getPath()->willReturn('/test-2'); - $routes[2]->getPath()->willReturn('/test-3'); - $this->chainGenerator->generate($children[0]->reveal())->willReturn($routes[0]->reveal()); - $this->chainGenerator->generate($children[1]->reveal())->willReturn($routes[1]->reveal()); - $this->chainGenerator->generate($children[2]->reveal())->willReturn($routes[2]->reveal()); - - $children[0]->setRoutePath('/test-1')->shouldBeCalled(); - $children[1]->setRoutePath('/test-2')->shouldBeCalled(); - $children[2]->setRoutePath('/test-3')->shouldBeCalled(); - - $nodes[0]->setProperty('i18n:de-routePath', '/test-1')->shouldBeCalled(); - $nodes[0]->setProperty('i18n:de-routePathName', 'i18n:de-routePath')->shouldBeCalled(); - $nodes[1]->setProperty('i18n:de-routePath', '/test-2')->shouldBeCalled(); - $nodes[1]->setProperty('i18n:de-routePathName', 'i18n:de-routePath')->shouldBeCalled(); - $nodes[2]->setProperty('i18n:de-routePath', '/test-3')->shouldBeCalled(); - $nodes[2]->setProperty('i18n:de-routePathName', 'i18n:de-routePath')->shouldBeCalled(); - - $this->routableSubscriber->handleReorder($event->reveal()); - } -} diff --git a/Tests/Unit/Domain/Model/ArticleDimensionContentTest.php b/Tests/Unit/Domain/Model/ArticleDimensionContentTest.php deleted file mode 100644 index cd43708d1..000000000 --- a/Tests/Unit/Domain/Model/ArticleDimensionContentTest.php +++ /dev/null @@ -1,82 +0,0 @@ - - */ - private $article; - - protected function setUp(): void - { - $this->article = $this->prophesize(ArticleInterface::class); - } - - public function testGetResource(): void - { - $articleDimensionContent = $this->createArticlDimensionContent(); - $this->assertSame($this->article->reveal(), $articleDimensionContent->getResource()); - } - - public function testTitleTemplateData(): void - { - $articleDimensionContent = $this->createArticlDimensionContent(); - $articleDimensionContent->setTemplateData(['title' => 'My Title']); - $this->assertSame('My Title', $articleDimensionContent->getTitle()); - } - - public function testTemplateData(): void - { - $articleDimensionContent = $this->createArticlDimensionContent(); - $articleDimensionContent->setTemplateData(['title' => 'My Title', 'description' => 'My Description']); - $this->assertSame( - [ - 'title' => 'My Title', - 'description' => 'My Description', - ], - $articleDimensionContent->getTemplateData() - ); - } - - public function testGetTemplateType(): void - { - $this->assertSame( - // use string instead of constant to test regression which maybe need migrations - 'article', - ArticleDimensionContent::getTemplateType() - ); - } - - public function testGetResourceKey(): void - { - $this->assertSame( - // use string instead of constant to test regression which maybe need migrations - 'articles', - ArticleDimensionContent::getResourceKey() - ); - } - - private function createArticlDimensionContent(): ArticleDimensionContentInterface - { - return new ArticleDimensionContent( - $this->article->reveal() - ); - } -} diff --git a/Tests/Unit/Domain/Model/ArticleTest.php b/Tests/Unit/Domain/Model/ArticleTest.php deleted file mode 100644 index bc2bb7730..000000000 --- a/Tests/Unit/Domain/Model/ArticleTest.php +++ /dev/null @@ -1,40 +0,0 @@ -createArticle(); - - $this->assertNotNull($article->getId()); - } - - public function testGetIdCustom() - { - $article = $this->createArticle(['id' => '9dd3f8c6-f000-4a37-a780-fe8c3128526d']); - - $this->assertSame('9dd3f8c6-f000-4a37-a780-fe8c3128526d', $article->getId()); - } - - private function createArticle(array $data = []): ArticleInterface - { - return new Article( - $data['id'] ?? null - ); - } -} diff --git a/Tests/Unit/Factory/ArticleResourceItemFactoryTest.php b/Tests/Unit/Factory/ArticleResourceItemFactoryTest.php deleted file mode 100644 index c76ab46a1..000000000 --- a/Tests/Unit/Factory/ArticleResourceItemFactoryTest.php +++ /dev/null @@ -1,73 +0,0 @@ -getArticleDocument(); - $articleViewDocument = $this->getArticleViewDocument($articleDocument); - $documentManager = $this->prophesize(DocumentManager::class); - $proxyFactory = $this->prophesize(LazyLoadingValueHolderFactory::class); - - $articleResourceItemFactory = new ArticleResourceItemFactory( - $documentManager->reveal(), - $proxyFactory->reveal() - ); - - $proxyFactory->createProxy(Argument::cetera()) - ->willReturn( - $this->prophesize(ArticleDocument::class)->willImplement(VirtualProxyInterface::class)->reveal() - ); - - $result = $articleResourceItemFactory->createResourceItem($articleViewDocument); - - $this->assertInstanceOf(VirtualProxyInterface::class, $result->getResource()); - $this->assertInstanceOf(ArticleDocument::class, $result->getResource()); - $this->assertInstanceOf(ArticleResourceItem::class, $result); - $this->assertEquals($result->getUuid(), $articleDocument->getUuid()); - } - - /** - * @return ArticleDocument - */ - private function getArticleDocument() - { - $articleDocument = new ArticleDocument(); - $articleDocument->setUuid('123-123-123'); - $articleDocument->setLocale('de'); - - return $articleDocument; - } - - /** - * @return ArticleViewDocument - */ - private function getArticleViewDocument(ArticleDocument $articleDocument) - { - $articleViewDocument = new ArticleViewDocument($articleDocument->getUuid()); - $articleViewDocument->setLocale($articleDocument->getLocale()); - - return $articleViewDocument; - } -} diff --git a/Tests/Unit/Infrastructure/Sulu/Admin/ArticleAdminTest.php b/Tests/Unit/Infrastructure/Sulu/Admin/ArticleAdminTest.php deleted file mode 100644 index 0000c20b3..000000000 --- a/Tests/Unit/Infrastructure/Sulu/Admin/ArticleAdminTest.php +++ /dev/null @@ -1,146 +0,0 @@ - - */ - private $contentViewBuilderFactory; - - /** - * @var ObjectProphecy - */ - private $securityChecker; - - /** - * @var ObjectProphecy - */ - private $localizationManager; - - /** - * @var ArticleAdmin - */ - private $articleAdmin; - - protected function setUp(): void - { - $this->viewBuilderFactory = new ViewBuilderFactory(); - $this->contentViewBuilderFactory = $this->prophesize(ContentViewBuilderFactoryInterface::class); - $this->securityChecker = $this->prophesize(SecurityCheckerInterface::class); - $this->localizationManager = $this->prophesize(LocalizationManagerInterface::class); - - $this->articleAdmin = new ArticleAdmin( - $this->viewBuilderFactory, - $this->contentViewBuilderFactory->reveal(), - $this->securityChecker->reveal(), - $this->localizationManager->reveal() - ); - } - - public function testConfigureViews(): void - { - $viewCollection = $this->prophesize(ViewCollection::class); - - $this->securityChecker->hasPermission(ArticleAdmin::SECURITY_CONTEXT, Argument::any()) - ->shouldBeCalled() - ->willReturn(true); - - $this->localizationManager->getLocales() - ->shouldBeCalled() - ->willReturn(['de', 'en']); - - $contentView = $this->prophesize(ViewBuilderInterface::class); - - $this->contentViewBuilderFactory->createViews( - ArticleInterface::class, - ArticleAdmin::EDIT_TABS_VIEW, - ArticleAdmin::ADD_TABS_VIEW, - ArticleAdmin::SECURITY_CONTEXT - ) - ->shouldBeCalled() - ->willReturn([$contentView->reveal()]); - - $viewCollection->add(Argument::any()) - ->shouldBeCalled(4); - - $this->articleAdmin->configureViews($viewCollection->reveal()); - } - - public function testConfigureNavigationItems(): void - { - $navigationItemCollection = $this->prophesize(NavigationItemCollection::class); - $navigationItemCollection->add(Argument::any()) - ->shouldBeCalledOnce(); - - $this->securityChecker->hasPermission(ArticleAdmin::SECURITY_CONTEXT, PermissionTypes::EDIT) - ->shouldBeCalled() - ->willReturn(true); - - $this->articleAdmin->configureNavigationItems($navigationItemCollection->reveal()); - } - - public function testConfigureNavigationItemsNoPermissions(): void - { - $navigationItemCollection = $this->prophesize(NavigationItemCollection::class); - $navigationItemCollection->add(Argument::any()) - ->shouldNotBeCalled(); - - $this->securityChecker->hasPermission(ArticleAdmin::SECURITY_CONTEXT, PermissionTypes::EDIT) - ->shouldBeCalled() - ->willReturn(false); - - $this->articleAdmin->configureNavigationItems($navigationItemCollection->reveal()); - } - - public function testGetSecurityContexts(): void - { - $this->assertSame( - [ - 'Sulu' => [ - 'Global' => [ - // using not the ArticleAdmin constant here to test regression which would need a migration - 'sulu.article.articles' => [ - PermissionTypes::VIEW, - PermissionTypes::ADD, - PermissionTypes::EDIT, - PermissionTypes::DELETE, - PermissionTypes::LIVE, - ], - ], - ], - ], - $this->articleAdmin->getSecurityContexts() - ); - } -} diff --git a/Tests/Unit/Infrastructure/Sulu/Headless/Content/ContentTypeResolver/ArticleSelectionResolverTest.php b/Tests/Unit/Infrastructure/Sulu/Headless/Content/ContentTypeResolver/ArticleSelectionResolverTest.php deleted file mode 100644 index 4cd10e62f..000000000 --- a/Tests/Unit/Infrastructure/Sulu/Headless/Content/ContentTypeResolver/ArticleSelectionResolverTest.php +++ /dev/null @@ -1,261 +0,0 @@ -structureResolver = $this->prophesize(StructureResolverInterface::class); - $this->contentQueryBuilder = $this->prophesize(ContentQueryBuilderInterface::class); - $this->contentMapper = $this->prophesize(ContentMapperInterface::class); - - $this->articleSelectionResolver = new ArticleSelectionResolver( - $this->structureResolver->reveal(), - $this->contentQueryBuilder->reveal(), - $this->contentMapper->reveal(), - true - ); - } - - public function testGetContentType(): void - { - self::assertSame('article_selection', $this->articleSelectionResolver::getContentType()); - } - - public function testResolve(): void - { - $structure = $this->prophesize(StructureInterface::class); - $structure->getWebspaceKey()->willReturn('webspace-key'); - - /** @var PropertyInterface|ObjectProphecy $property */ - $property = $this->prophesize(PropertyInterface::class); - $params = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - new PropertyParameter('categories', 'excerpt.categories'), - ]), - ]; - - $property->getParams()->willReturn($params); - $property->getStructure()->willReturn($structure->reveal()); - - // expected and unexpected service calls - $this->contentQueryBuilder->init([ - 'ids' => ['article-id-1', 'article-id-2'], - 'properties' => $params['properties']->getValue(), - 'published' => false, - ])->shouldBeCalled(); - $this->contentQueryBuilder->build('webspace-key', ['en'])->willReturn(['article-query-string']); - - $articleStructure1 = $this->prophesize(StructureInterface::class); - $articleStructure1->getUuid()->willReturn('article-id-1'); - $articleStructure2 = $this->prophesize(StructureInterface::class); - $articleStructure2->getUuid()->willReturn('article-id-2'); - - $this->contentMapper->loadBySql2( - 'article-query-string', - 'en', - 'webspace-key' - )->willReturn([ - $articleStructure2->reveal(), - $articleStructure1->reveal(), - ])->shouldBeCalledOnce(); - $this->structureResolver->resolveProperties( - $articleStructure1->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - 'categories' => 'excerpt.categories', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure2->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - 'categories' => 'excerpt.categories', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ])->shouldBeCalledOnce(); - - // call test function - $result = $this->articleSelectionResolver->resolve( - ['article-id-1', 'article-id-2'], - $property->reveal(), - 'en' - ); - - $this->assertInstanceOf(ContentView::class, $result); - $this->assertSame( - [ - [ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ], - [ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ], - ], - $result->getContent() - ); - - $this->assertSame( - ['ids' => ['article-id-1', 'article-id-2']], - $result->getView() - ); - } - - public function testResolveDataIsNull(): void - { - $locale = 'en'; - $property = $this->prophesize(PropertyInterface::class); - - // expected and unexpected service calls - $this->contentQueryBuilder->init(Argument::cetera()) - ->shouldNotBeCalled(); - - $this->structureResolver->resolve(Argument::cetera()) - ->shouldNotBeCalled(); - - // call test function - $result = $this->articleSelectionResolver->resolve(null, $property->reveal(), $locale); - - $this->assertSame([], $result->getContent()); - - $this->assertSame(['ids' => []], $result->getView()); - } - - public function testResolveDataIsEmptyArray(): void - { - $locale = 'en'; - $property = $this->prophesize(PropertyInterface::class); - - // expected and unexpected service calls - $this->contentQueryBuilder->init(Argument::any()) - ->shouldNotBeCalled(); - - $this->structureResolver->resolve(Argument::any()) - ->shouldNotBeCalled(); - - // call test function - $result = $this->articleSelectionResolver->resolve([], $property->reveal(), $locale); - - $this->assertSame([], $result->getContent()); - - $this->assertSame(['ids' => []], $result->getView()); - } -} diff --git a/Tests/Unit/Infrastructure/Sulu/Headless/Content/ContentTypeResolver/SingleArticleSelectionResolverTest.php b/Tests/Unit/Infrastructure/Sulu/Headless/Content/ContentTypeResolver/SingleArticleSelectionResolverTest.php deleted file mode 100644 index 98589d240..000000000 --- a/Tests/Unit/Infrastructure/Sulu/Headless/Content/ContentTypeResolver/SingleArticleSelectionResolverTest.php +++ /dev/null @@ -1,115 +0,0 @@ -articleSelectionResolver = $this->prophesize(ArticleSelectionResolver::class); - - $this->singleArticleSelectionResolver = new SingleArticleSelectionResolver( - $this->articleSelectionResolver->reveal() - ); - } - - public function testGetContentType(): void - { - self::assertSame('single_article_selection', $this->singleArticleSelectionResolver::getContentType()); - } - - public function testResolve(): void - { - $property = $this->prophesize(PropertyInterface::class); - $this->articleSelectionResolver->resolve([1], $property, 'en', [])->willReturn( - new ContentView( - [ - [ - 'id' => '1', - 'uuid' => '1', - 'nodeType' => 1, - 'path' => '/testarticle', - 'changer' => 1, - 'publishedState' => true, - 'creator' => 1, - 'title' => 'TestArticle', - 'locale' => 'en', - 'webspaceKey' => 'sulu', - 'template' => 'headless', - 'parent' => '1', - 'author' => '2', - ], - ], - [1] - ) - ); - - $result = $this->singleArticleSelectionResolver->resolve(1, $property->reveal(), 'en'); - - $this->assertInstanceOf(ContentView::class, $result); - $this->assertSame( - [ - 'id' => '1', - 'uuid' => '1', - 'nodeType' => 1, - 'path' => '/testarticle', - 'changer' => 1, - 'publishedState' => true, - 'creator' => 1, - 'title' => 'TestArticle', - 'locale' => 'en', - 'webspaceKey' => 'sulu', - 'template' => 'headless', - 'parent' => '1', - 'author' => '2', - ], - $result->getContent() - ); - $this->assertSame( - [ - 'id' => 1, - ], - $result->getView() - ); - } - - public function testResolveDataIsNull(): void - { - $locale = 'en'; - $property = $this->prophesize(PropertyInterface::class); - - $result = $this->singleArticleSelectionResolver->resolve(null, $property->reveal(), $locale); - - $this->assertNull($result->getContent()); - - $this->assertSame(['id' => null], $result->getView()); - } -} diff --git a/Tests/Unit/Infrastructure/Sulu/Headless/Content/DataProviderResolver/ArticleDataProviderResolverTest.php b/Tests/Unit/Infrastructure/Sulu/Headless/Content/DataProviderResolver/ArticleDataProviderResolverTest.php deleted file mode 100644 index a2f35f0ea..000000000 --- a/Tests/Unit/Infrastructure/Sulu/Headless/Content/DataProviderResolver/ArticleDataProviderResolverTest.php +++ /dev/null @@ -1,284 +0,0 @@ -articleDataProvider = $this->prophesize(DataProviderInterface::class); - $this->structureResolver = $this->prophesize(StructureResolverInterface::class); - $this->contentQueryBuilder = $this->prophesize(ContentQueryBuilderInterface::class); - $this->contentMapper = $this->prophesize(ContentMapperInterface::class); - - $this->articleDataProviderResolver = new ArticleDataProviderResolver( - $this->articleDataProvider->reveal(), - $this->structureResolver->reveal(), - $this->contentQueryBuilder->reveal(), - $this->contentMapper->reveal(), - true - ); - } - - public function testGetDataProvider(): void - { - self::assertSame('articles', $this->articleDataProviderResolver::getDataProvider()); - } - - public function testGetProviderConfiguration(): void - { - $configuration = $this->prophesize(ProviderConfigurationInterface::class); - $this->articleDataProvider->getConfiguration()->willReturn($configuration->reveal()); - - $this->assertSame($configuration->reveal(), $this->articleDataProviderResolver->getProviderConfiguration()); - } - - public function testGetProviderDefaultParams(): void - { - $propertyParameter = $this->prophesize(PropertyParameter::class); - $this->articleDataProvider->getDefaultPropertyParameter()->willReturn(['test' => $propertyParameter->reveal()]); - - $this->assertSame(['test' => $propertyParameter->reveal()], $this->articleDataProviderResolver->getProviderDefaultParams()); - } - - public function testResolve(): void - { - $providerResultItem1 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem1->getId()->willReturn('article-id-1'); - - $providerResultItem2 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem2->getId()->willReturn('article-id-2'); - - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(true); - $providerResult->getItems()->willReturn([$providerResultItem1->reveal(), $providerResultItem2->reveal()]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal())->shouldBeCalledOnce(); - - $this->contentQueryBuilder->init([ - 'ids' => ['article-id-1', 'article-id-2'], - 'properties' => $propertyParameters['properties']->getValue(), - 'published' => false, - ])->shouldBeCalled(); - $this->contentQueryBuilder->build('webspace-key', ['en'])->willReturn(['article-query-string']); - - $articleStructure1 = $this->prophesize(StructureInterface::class); - $articleStructure1->getUuid()->willReturn('article-id-1'); - $articleStructure2 = $this->prophesize(StructureInterface::class); - $articleStructure2->getUuid()->willReturn('article-id-2'); - $this->contentMapper->loadBySql2( - 'article-query-string', - 'en', - 'webspace-key' - )->willReturn([ - $articleStructure2->reveal(), - $articleStructure1->reveal(), - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure1->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure2->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertTrue($result->getHasNextPage()); - $this->assertSame( - [ - [ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - [ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - ], - $result->getItems() - ); - } - - public function testResolveEmptyProviderResult(): void - { - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(false); - $providerResult->getItems()->willReturn([]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal()) - ->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertFalse($result->getHasNextPage()); - $this->assertSame( - [], - $result->getItems() - ); - } -} diff --git a/Tests/Unit/Infrastructure/Sulu/Headless/Content/DataProviderResolver/ArticlePageTreeDataProviderResolverTest.php b/Tests/Unit/Infrastructure/Sulu/Headless/Content/DataProviderResolver/ArticlePageTreeDataProviderResolverTest.php deleted file mode 100644 index 61f02f671..000000000 --- a/Tests/Unit/Infrastructure/Sulu/Headless/Content/DataProviderResolver/ArticlePageTreeDataProviderResolverTest.php +++ /dev/null @@ -1,284 +0,0 @@ -articleDataProvider = $this->prophesize(DataProviderInterface::class); - $this->structureResolver = $this->prophesize(StructureResolverInterface::class); - $this->contentQueryBuilder = $this->prophesize(ContentQueryBuilderInterface::class); - $this->contentMapper = $this->prophesize(ContentMapperInterface::class); - - $this->articleDataProviderResolver = new ArticlePageTreeDataProviderResolver( - $this->articleDataProvider->reveal(), - $this->structureResolver->reveal(), - $this->contentQueryBuilder->reveal(), - $this->contentMapper->reveal(), - true - ); - } - - public function testGetDataProvider(): void - { - self::assertSame('articles_page_tree', $this->articleDataProviderResolver::getDataProvider()); - } - - public function testGetProviderConfiguration(): void - { - $configuration = $this->prophesize(ProviderConfigurationInterface::class); - $this->articleDataProvider->getConfiguration()->willReturn($configuration->reveal()); - - $this->assertSame($configuration->reveal(), $this->articleDataProviderResolver->getProviderConfiguration()); - } - - public function testGetProviderDefaultParams(): void - { - $propertyParameter = $this->prophesize(PropertyParameter::class); - $this->articleDataProvider->getDefaultPropertyParameter()->willReturn(['test' => $propertyParameter->reveal()]); - - $this->assertSame(['test' => $propertyParameter->reveal()], $this->articleDataProviderResolver->getProviderDefaultParams()); - } - - public function testResolve(): void - { - $providerResultItem1 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem1->getId()->willReturn('article-id-1'); - - $providerResultItem2 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem2->getId()->willReturn('article-id-2'); - - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(true); - $providerResult->getItems()->willReturn([$providerResultItem1->reveal(), $providerResultItem2->reveal()]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal())->shouldBeCalledOnce(); - - $this->contentQueryBuilder->init([ - 'ids' => ['article-id-1', 'article-id-2'], - 'properties' => $propertyParameters['properties']->getValue(), - 'published' => false, - ])->shouldBeCalled(); - $this->contentQueryBuilder->build('webspace-key', ['en'])->willReturn(['article-query-string']); - - $articleStructure1 = $this->prophesize(StructureInterface::class); - $articleStructure1->getUuid()->willReturn('article-id-1'); - $articleStructure2 = $this->prophesize(StructureInterface::class); - $articleStructure2->getUuid()->willReturn('article-id-2'); - $this->contentMapper->loadBySql2( - 'article-query-string', - 'en', - 'webspace-key' - )->willReturn([ - $articleStructure2->reveal(), - $articleStructure1->reveal(), - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure1->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure2->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertTrue($result->getHasNextPage()); - $this->assertSame( - [ - [ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - [ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - ], - $result->getItems() - ); - } - - public function testResolveEmptyProviderResult(): void - { - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(false); - $providerResult->getItems()->willReturn([]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal()) - ->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertFalse($result->getHasNextPage()); - $this->assertSame( - [], - $result->getItems() - ); - } -} diff --git a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/ContentTypeResolver/ArticleSelectionResolverTest.php b/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/ContentTypeResolver/ArticleSelectionResolverTest.php deleted file mode 100644 index 800368730..000000000 --- a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/ContentTypeResolver/ArticleSelectionResolverTest.php +++ /dev/null @@ -1,261 +0,0 @@ -structureResolver = $this->prophesize(StructureResolverInterface::class); - $this->contentQueryBuilder = $this->prophesize(ContentQueryBuilderInterface::class); - $this->contentMapper = $this->prophesize(ContentMapperInterface::class); - - $this->articleSelectionResolver = new ArticleSelectionResolver( - $this->structureResolver->reveal(), - $this->contentQueryBuilder->reveal(), - $this->contentMapper->reveal(), - true - ); - } - - public function testGetContentType(): void - { - self::assertSame('article_selection', $this->articleSelectionResolver::getContentType()); - } - - public function testResolve(): void - { - $structure = $this->prophesize(StructureInterface::class); - $structure->getWebspaceKey()->willReturn('webspace-key'); - - /** @var PropertyInterface|ObjectProphecy $property */ - $property = $this->prophesize(PropertyInterface::class); - $params = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - new PropertyParameter('categories', 'excerpt.categories'), - ]), - ]; - - $property->getParams()->willReturn($params); - $property->getStructure()->willReturn($structure->reveal()); - - // expected and unexpected service calls - $this->contentQueryBuilder->init([ - 'ids' => ['article-id-1', 'article-id-2'], - 'properties' => $params['properties']->getValue(), - 'published' => false, - ])->shouldBeCalled(); - $this->contentQueryBuilder->build('webspace-key', ['en'])->willReturn(['article-query-string']); - - $articleStructure1 = $this->prophesize(StructureInterface::class); - $articleStructure1->getUuid()->willReturn('article-id-1'); - $articleStructure2 = $this->prophesize(StructureInterface::class); - $articleStructure2->getUuid()->willReturn('article-id-2'); - - $this->contentMapper->loadBySql2( - 'article-query-string', - 'en', - 'webspace-key' - )->willReturn([ - $articleStructure2->reveal(), - $articleStructure1->reveal(), - ])->shouldBeCalledOnce(); - $this->structureResolver->resolveProperties( - $articleStructure1->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - 'categories' => 'excerpt.categories', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure2->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - 'categories' => 'excerpt.categories', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ])->shouldBeCalledOnce(); - - // call test function - $result = $this->articleSelectionResolver->resolve( - ['article-id-1', 'article-id-2'], - $property->reveal(), - 'en' - ); - - $this->assertInstanceOf(ContentView::class, $result); - $this->assertSame( - [ - [ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ], - [ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - 'categories' => [], - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - 'categories' => [], - ], - ], - ], - $result->getContent() - ); - - $this->assertSame( - ['ids' => ['article-id-1', 'article-id-2']], - $result->getView() - ); - } - - public function testResolveDataIsNull(): void - { - $locale = 'en'; - $property = $this->prophesize(PropertyInterface::class); - - // expected and unexpected service calls - $this->contentQueryBuilder->init(Argument::cetera()) - ->shouldNotBeCalled(); - - $this->structureResolver->resolve(Argument::cetera()) - ->shouldNotBeCalled(); - - // call test function - $result = $this->articleSelectionResolver->resolve(null, $property->reveal(), $locale); - - $this->assertSame([], $result->getContent()); - - $this->assertSame(['ids' => []], $result->getView()); - } - - public function testResolveDataIsEmptyArray(): void - { - $locale = 'en'; - $property = $this->prophesize(PropertyInterface::class); - - // expected and unexpected service calls - $this->contentQueryBuilder->init(Argument::any()) - ->shouldNotBeCalled(); - - $this->structureResolver->resolve(Argument::any()) - ->shouldNotBeCalled(); - - // call test function - $result = $this->articleSelectionResolver->resolve([], $property->reveal(), $locale); - - $this->assertSame([], $result->getContent()); - - $this->assertSame(['ids' => []], $result->getView()); - } -} diff --git a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/ContentTypeResolver/SingleArticleSelectionResolverTest.php b/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/ContentTypeResolver/SingleArticleSelectionResolverTest.php deleted file mode 100644 index 22610a4f9..000000000 --- a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/ContentTypeResolver/SingleArticleSelectionResolverTest.php +++ /dev/null @@ -1,115 +0,0 @@ -articleSelectionResolver = $this->prophesize(ArticleSelectionResolver::class); - - $this->singleArticleSelectionResolver = new SingleArticleSelectionResolver( - $this->articleSelectionResolver->reveal() - ); - } - - public function testGetContentType(): void - { - self::assertSame('single_article_selection', $this->singleArticleSelectionResolver::getContentType()); - } - - public function testResolve(): void - { - $property = $this->prophesize(PropertyInterface::class); - $this->articleSelectionResolver->resolve([1], $property, 'en', [])->willReturn( - new ContentView( - [ - [ - 'id' => '1', - 'uuid' => '1', - 'nodeType' => 1, - 'path' => '/testarticle', - 'changer' => 1, - 'publishedState' => true, - 'creator' => 1, - 'title' => 'TestArticle', - 'locale' => 'en', - 'webspaceKey' => 'sulu', - 'template' => 'headless', - 'parent' => '1', - 'author' => '2', - ], - ], - [1] - ) - ); - - $result = $this->singleArticleSelectionResolver->resolve(1, $property->reveal(), 'en'); - - $this->assertInstanceOf(ContentView::class, $result); - $this->assertSame( - [ - 'id' => '1', - 'uuid' => '1', - 'nodeType' => 1, - 'path' => '/testarticle', - 'changer' => 1, - 'publishedState' => true, - 'creator' => 1, - 'title' => 'TestArticle', - 'locale' => 'en', - 'webspaceKey' => 'sulu', - 'template' => 'headless', - 'parent' => '1', - 'author' => '2', - ], - $result->getContent() - ); - $this->assertSame( - [ - 'id' => 1, - ], - $result->getView() - ); - } - - public function testResolveDataIsNull(): void - { - $locale = 'en'; - $property = $this->prophesize(PropertyInterface::class); - - $result = $this->singleArticleSelectionResolver->resolve(null, $property->reveal(), $locale); - - $this->assertNull($result->getContent()); - - $this->assertSame(['id' => null], $result->getView()); - } -} diff --git a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/DataProviderResolver/ArticleDataProviderResolverTest.php b/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/DataProviderResolver/ArticleDataProviderResolverTest.php deleted file mode 100644 index 3b5a287b1..000000000 --- a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/DataProviderResolver/ArticleDataProviderResolverTest.php +++ /dev/null @@ -1,284 +0,0 @@ -articleDataProvider = $this->prophesize(DataProviderInterface::class); - $this->structureResolver = $this->prophesize(StructureResolverInterface::class); - $this->contentQueryBuilder = $this->prophesize(ContentQueryBuilderInterface::class); - $this->contentMapper = $this->prophesize(ContentMapperInterface::class); - - $this->articleDataProviderResolver = new ArticleDataProviderResolver( - $this->articleDataProvider->reveal(), - $this->structureResolver->reveal(), - $this->contentQueryBuilder->reveal(), - $this->contentMapper->reveal(), - true - ); - } - - public function testGetDataProvider(): void - { - self::assertSame('articles', $this->articleDataProviderResolver::getDataProvider()); - } - - public function testGetProviderConfiguration(): void - { - $configuration = $this->prophesize(ProviderConfigurationInterface::class); - $this->articleDataProvider->getConfiguration()->willReturn($configuration->reveal()); - - $this->assertSame($configuration->reveal(), $this->articleDataProviderResolver->getProviderConfiguration()); - } - - public function testGetProviderDefaultParams(): void - { - $propertyParameter = $this->prophesize(PropertyParameter::class); - $this->articleDataProvider->getDefaultPropertyParameter()->willReturn(['test' => $propertyParameter->reveal()]); - - $this->assertSame(['test' => $propertyParameter->reveal()], $this->articleDataProviderResolver->getProviderDefaultParams()); - } - - public function testResolve(): void - { - $providerResultItem1 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem1->getId()->willReturn('article-id-1'); - - $providerResultItem2 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem2->getId()->willReturn('article-id-2'); - - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(true); - $providerResult->getItems()->willReturn([$providerResultItem1->reveal(), $providerResultItem2->reveal()]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal())->shouldBeCalledOnce(); - - $this->contentQueryBuilder->init([ - 'ids' => ['article-id-1', 'article-id-2'], - 'properties' => $propertyParameters['properties']->getValue(), - 'published' => false, - ])->shouldBeCalled(); - $this->contentQueryBuilder->build('webspace-key', ['en'])->willReturn(['article-query-string']); - - $articleStructure1 = $this->prophesize(StructureInterface::class); - $articleStructure1->getUuid()->willReturn('article-id-1'); - $articleStructure2 = $this->prophesize(StructureInterface::class); - $articleStructure2->getUuid()->willReturn('article-id-2'); - $this->contentMapper->loadBySql2( - 'article-query-string', - 'en', - 'webspace-key' - )->willReturn([ - $articleStructure2->reveal(), - $articleStructure1->reveal(), - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure1->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure2->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertTrue($result->getHasNextPage()); - $this->assertSame( - [ - [ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - [ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - ], - $result->getItems() - ); - } - - public function testResolveEmptyProviderResult(): void - { - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(false); - $providerResult->getItems()->willReturn([]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal()) - ->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertFalse($result->getHasNextPage()); - $this->assertSame( - [], - $result->getItems() - ); - } -} diff --git a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/DataProviderResolver/ArticlePageTreeDataProviderResolverTest.php b/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/DataProviderResolver/ArticlePageTreeDataProviderResolverTest.php deleted file mode 100644 index e75068c98..000000000 --- a/Tests/Unit/Infrastructure/SuluHeadlessBundle/Content/DataProviderResolver/ArticlePageTreeDataProviderResolverTest.php +++ /dev/null @@ -1,284 +0,0 @@ -articleDataProvider = $this->prophesize(DataProviderInterface::class); - $this->structureResolver = $this->prophesize(StructureResolverInterface::class); - $this->contentQueryBuilder = $this->prophesize(ContentQueryBuilderInterface::class); - $this->contentMapper = $this->prophesize(ContentMapperInterface::class); - - $this->articleDataProviderResolver = new ArticlePageTreeDataProviderResolver( - $this->articleDataProvider->reveal(), - $this->structureResolver->reveal(), - $this->contentQueryBuilder->reveal(), - $this->contentMapper->reveal(), - true - ); - } - - public function testGetDataProvider(): void - { - self::assertSame('articles_page_tree', $this->articleDataProviderResolver::getDataProvider()); - } - - public function testGetProviderConfiguration(): void - { - $configuration = $this->prophesize(ProviderConfigurationInterface::class); - $this->articleDataProvider->getConfiguration()->willReturn($configuration->reveal()); - - $this->assertSame($configuration->reveal(), $this->articleDataProviderResolver->getProviderConfiguration()); - } - - public function testGetProviderDefaultParams(): void - { - $propertyParameter = $this->prophesize(PropertyParameter::class); - $this->articleDataProvider->getDefaultPropertyParameter()->willReturn(['test' => $propertyParameter->reveal()]); - - $this->assertSame(['test' => $propertyParameter->reveal()], $this->articleDataProviderResolver->getProviderDefaultParams()); - } - - public function testResolve(): void - { - $providerResultItem1 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem1->getId()->willReturn('article-id-1'); - - $providerResultItem2 = $this->prophesize(ResourceItemInterface::class); - $providerResultItem2->getId()->willReturn('article-id-2'); - - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(true); - $providerResult->getItems()->willReturn([$providerResultItem1->reveal(), $providerResultItem2->reveal()]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal())->shouldBeCalledOnce(); - - $this->contentQueryBuilder->init([ - 'ids' => ['article-id-1', 'article-id-2'], - 'properties' => $propertyParameters['properties']->getValue(), - 'published' => false, - ])->shouldBeCalled(); - $this->contentQueryBuilder->build('webspace-key', ['en'])->willReturn(['article-query-string']); - - $articleStructure1 = $this->prophesize(StructureInterface::class); - $articleStructure1->getUuid()->willReturn('article-id-1'); - $articleStructure2 = $this->prophesize(StructureInterface::class); - $articleStructure2->getUuid()->willReturn('article-id-2'); - $this->contentMapper->loadBySql2( - 'article-query-string', - 'en', - 'webspace-key' - )->willReturn([ - $articleStructure2->reveal(), - $articleStructure1->reveal(), - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure1->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - $this->structureResolver->resolveProperties( - $articleStructure2->reveal(), - [ - 'title' => 'title', - 'routePath' => 'routePath', - 'contentDescription' => 'description', - 'excerptTitle' => 'excerpt.title', - ], - 'en' - )->willReturn([ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ])->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertTrue($result->getHasNextPage()); - $this->assertSame( - [ - [ - 'id' => 'article-id-1', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 1', - 'routePath' => '/article-url-1', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 1', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - [ - 'id' => 'article-id-2', - 'template' => 'default', - 'content' => [ - 'title' => 'Article Title 2', - 'routePath' => '/article-url-2', - 'contentDescription' => 'Article Content Description', - 'excerptTitle' => 'Article Excerpt Title 2', - ], - 'view' => [ - 'title' => [], - 'routePath' => [], - 'contentDescription' => [], - 'excerptTitle' => [], - ], - ], - ], - $result->getItems() - ); - } - - public function testResolveEmptyProviderResult(): void - { - $providerResult = $this->prophesize(DataProviderResult::class); - $providerResult->getHasNextPage()->willReturn(false); - $providerResult->getItems()->willReturn([]); - - $propertyParameters = [ - 'properties' => new PropertyParameter('properties', [ - new PropertyParameter('contentDescription', 'description'), - new PropertyParameter('excerptTitle', 'excerpt.title'), - ]), - ]; - - // expected and unexpected service calls - $this->articleDataProvider->resolveResourceItems( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - )->willReturn($providerResult->reveal()) - ->shouldBeCalledOnce(); - - // call test function - $result = $this->articleDataProviderResolver->resolve( - ['filter-key' => 'filter-value'], - $propertyParameters, - ['webspaceKey' => 'webspace-key', 'locale' => 'en'], - 10, - 1, - 5 - ); - - $this->assertFalse($result->getHasNextPage()); - $this->assertSame( - [], - $result->getItems() - ); - } -} diff --git a/Tests/Unit/ListBuilder/ElasticSearchFieldDescriptorBuilderTest.php b/Tests/Unit/ListBuilder/ElasticSearchFieldDescriptorBuilderTest.php deleted file mode 100644 index 67636e883..000000000 --- a/Tests/Unit/ListBuilder/ElasticSearchFieldDescriptorBuilderTest.php +++ /dev/null @@ -1,75 +0,0 @@ -build(); - $this->assertInstanceOf(ElasticSearchFieldDescriptor::class, $fieldDescriptor); - $this->assertEquals('title', $fieldDescriptor->getName()); - $this->assertEquals('public.title', $fieldDescriptor->getTranslation()); - $this->assertFalse($fieldDescriptor->getSortable()); - $this->assertFalse($fieldDescriptor->getDisabled()); - $this->assertFalse($fieldDescriptor->getDefault()); - $this->assertEquals('string', $fieldDescriptor->getType()); - } - - public function testConstructor() - { - $builder = new ElasticSearchFieldDescriptorBuilder('title', 'public.title'); - - $fieldDescriptor = $builder->build(); - $this->assertInstanceOf(ElasticSearchFieldDescriptor::class, $fieldDescriptor); - $this->assertEquals('title', $fieldDescriptor->getName()); - $this->assertEquals('public.title', $fieldDescriptor->getTranslation()); - } - - public function testSetVisibility() - { - $builder = new ElasticSearchFieldDescriptorBuilder('title', 'public.title'); - - $builder->setVisibility(FieldDescriptorInterface::VISIBILITY_ALWAYS); - - $fieldDescriptor = $builder->build(); - $this->assertSame(FieldDescriptorInterface::VISIBILITY_ALWAYS, $fieldDescriptor->getVisibility()); - } - - public function testSetSortField() - { - $builder = new ElasticSearchFieldDescriptorBuilder('title', 'public.title'); - - $builder->setSortField('title.raw'); - - $fieldDescriptor = $builder->build(); - $this->assertEquals('title.raw', $fieldDescriptor->getSortField()); - $this->assertTrue($fieldDescriptor->getSortable()); - } - - public function testSetType() - { - $builder = new ElasticSearchFieldDescriptorBuilder('title', 'public.title'); - - $builder->setType('boolean'); - - $fieldDescriptor = $builder->build(); - $this->assertEquals('boolean', $fieldDescriptor->getType()); - } -} diff --git a/Tests/Unit/Preview/ArticleObjectProviderTest.php b/Tests/Unit/Preview/ArticleObjectProviderTest.php deleted file mode 100644 index 9ed285347..000000000 --- a/Tests/Unit/Preview/ArticleObjectProviderTest.php +++ /dev/null @@ -1,264 +0,0 @@ -documentManager = $this->prophesize(DocumentManagerInterface::class); - $this->serializer = $this->prophesize(SerializerInterface::class); - $this->structureMetadataFactory = $this->prophesize(StructureMetadataFactoryInterface::class); - - $this->provider = new ArticleObjectProvider( - $this->documentManager->reveal(), - $this->serializer->reveal(), - ArticleDocument::class, - $this->structureMetadataFactory->reveal() - ); - } - - public function testGetObject($id = '123-123-123', $locale = 'de') - { - $this->documentManager->find($id, $locale, Argument::any()) - ->willReturn($this->prophesize(ArticleDocument::class)->reveal())->shouldBeCalledTimes(1); - - $this->assertInstanceOf(ArticleDocument::class, $this->provider->getObject($id, $locale)); - } - - public function testGetId($id = '123-123-123') - { - $object = $this->prophesize(ArticleDocument::class); - $object->getUuid()->willReturn($id); - - $this->assertEquals($id, $this->provider->getId($object->reveal())); - } - - public function testSetValues($locale = 'de', $data = ['title' => 'SULU']) - { - $structure = new Structure(); - $object = $this->prophesize(ArticleDocument::class); - $object->getStructure()->willReturn($structure); - - $this->provider->setValues($object->reveal(), $locale, $data); - - $this->assertEquals('SULU', $structure->getProperty('title')->getValue()); - } - - public function testSetExtensionValues(string $locale = 'de', array $data = ['title' => 'SULU', 'ext' => ['key' => 'value']]): void - { - $structure = new Structure(); - $object = $this->prophesize(ArticleDocument::class); - $object->setExtensionsData( - Argument::that( - function($extensionContainer) { - $this->assertEquals(['key' => 'value'], $extensionContainer->toArray()); - - return true; - } - ) - )->shouldBeCalled(); - $object->getStructure()->willReturn($structure); - - $this->provider->setValues($object->reveal(), $locale, $data); - - $this->assertEquals('SULU', $structure->getProperty('title')->getValue()); - } - - public function testSetContext($locale = 'de', $context = ['template' => 'test-template']) - { - $object = $this->prophesize(ArticleDocument::class); - $object->setStructureType('test-template')->shouldBeCalled(); - - $this->assertEquals($object->reveal(), $this->provider->setContext($object->reveal(), $locale, $context)); - } - - public function testSerialize() - { - $object = $this->prophesize(ArticleDocument::class); - $object->getPageNumber()->willReturn(1); - - $this->serializer->serialize( - $object->reveal(), - 'json', - Argument::that( - function(SerializationContext $context) { - return $context->shouldSerializeNull() - && $context->getAttribute('groups') === ['preview']; - } - ) - )->shouldBeCalled()->willReturn('{"title": "test"}'); - - $this->assertEquals( - '{"pageNumber":1,"object":"{\"title\": \"test\"}"}', - $this->provider->serialize($object->reveal()) - ); - } - - public function testSerializePage() - { - $article = $this->prophesize(ArticleDocument::class); - $article->getPageNumber()->willReturn(1); - $article->getTitle()->willReturn('page 1'); - - $object = $this->prophesize(ArticlePageDocument::class); - $object->getPageNumber()->willReturn(2); - $object->getTitle()->willReturn('page 2'); - $object->getParent()->willReturn($article->reveal()); - - $this->serializer->serialize( - $article->reveal(), - 'json', - Argument::that( - function(SerializationContext $context) { - return $context->shouldSerializeNull() - && $context->getAttribute('groups') === ['preview']; - } - ) - )->shouldBeCalled()->willReturn('{"title": "test"}'); - - $this->assertEquals( - '{"pageNumber":2,"object":"{\"title\": \"test\"}"}', - $this->provider->serialize($object->reveal()) - ); - } - - public function testDeserialize() - { - $object = $this->prophesize(ArticleDocument::class); - - $this->serializer->deserialize( - '{"title": "test"}', - ArticleDocument::class, - 'json', - Argument::that( - function(DeserializationContext $context) { - return $context->getAttribute('groups') === ['preview']; - } - ) - )->shouldBeCalled()->willReturn($object->reveal()); - - $object->getChildren()->willReturn([]); - - $this->assertEquals( - $object->reveal(), - $this->provider->deserialize( - '{"pageNumber":1,"object":"{\"title\": \"test\"}"}', - \get_class($object->reveal()) - ) - ); - } - - public function testDeserializePage() - { - $article = $this->prophesize(ArticleDocument::class); - - $object = $this->prophesize(ArticlePageDocument::class); - $page2 = $this->prophesize(ArticlePageDocument::class); - - $this->serializer->deserialize( - '{"title": "test"}', - ArticleDocument::class, - 'json', - Argument::that( - function(DeserializationContext $context) { - return $context->getAttribute('groups') === ['preview']; - } - ) - )->shouldBeCalled()->willReturn($article->reveal()); - - $article->getChildren()->willReturn(['page-1' => $object->reveal(), 'page-2' => $page2->reveal()]); - $object->setParent($article->reveal())->shouldBeCalled(); - $page2->setParent($article->reveal())->shouldBeCalled(); - - $this->assertEquals( - $object->reveal(), - $this->provider->deserialize( - '{"pageNumber":2,"object":"{\"title\": \"test\"}"}', - \get_class($object->reveal()) - ) - ); - } - - public function testGetSecurityContext(): void - { - $metadata = $this->prophesize(StructureMetadata::class); - $metadata->hasTag(ArticleAdmin::STRUCTURE_TAG_TYPE)->willReturn(true); - $metadata->getTag(ArticleAdmin::STRUCTURE_TAG_TYPE)->willReturn([ - 'attributes' => ['type' => 'test-type'], - ]); - - $this->structureMetadataFactory->getStructureMetadata('article', 'default')->willReturn($metadata->reveal()); - - $object = $this->prophesize(ArticleDocument::class); - $object->getStructureType()->willReturn('default'); - $this->documentManager->find('123-123-213', 'en', Argument::any()) - ->willReturn($object->reveal()); - - $this->assertSame( - ArticleAdmin::getArticleSecurityContext('test-type'), - $this->provider->getSecurityContext('123-123-213', 'en') - ); - } - - public function testGetSecurityContextNoMetadata(): void - { - $this->structureMetadataFactory->getStructureMetadata('article', 'default')->willReturn(null); - - $object = $this->prophesize(ArticleDocument::class); - $object->getStructureType()->willReturn('default'); - $this->documentManager->find('123-123-213', 'en', Argument::any()) - ->willReturn($object->reveal()); - - $this->assertSame( - ArticleAdmin::SECURITY_CONTEXT, - $this->provider->getSecurityContext('123-123-213', 'en') - ); - } -} diff --git a/Tests/Unit/Repository/ArticleViewDocumentRepositoryTest.php b/Tests/Unit/Repository/ArticleViewDocumentRepositoryTest.php deleted file mode 100644 index 84def7ddb..000000000 --- a/Tests/Unit/Repository/ArticleViewDocumentRepositoryTest.php +++ /dev/null @@ -1,234 +0,0 @@ -search = $this->prophesize(Search::class); - - $this->repository = $this->prophesize(Repository::class); - $this->repository->createSearch()->willReturn(new Search()); - - $this->searchManager = $this->prophesize(Manager::class); - $this->searchManager->getRepository(ArticleViewDocument::class)->willReturn($this->repository->reveal()); - - $this->articleViewDocumentRepository = new ArticleViewDocumentRepository( - $this->searchManager->reveal(), - ArticleViewDocument::class, - ['title', 'teaser_description'] - ); - } - - public function dataProvider() - { - return [ - [], - ['123-123-123', ['blog', 'article']], - ['321-321-321', ['blog'], 'en', 10], - ['444-444-444', ['blog'], 'en', 10, 'test_webspace'], - ]; - } - - /** - * @dataProvider dataProvider - * - * @param string $uuid - * @param string $locale - * @param int $limit - * @param string $webspaceKey - */ - public function testFindSimilar( - $uuid = '123-123-123', - array $types = ['blog'], - $locale = 'de', - $limit = 12, - $webspaceKey = null - ) { - $termQuery = []; - foreach ($types as $type) { - $termQuery[] = [ - 'term' => ['type' => $type], - ]; - } - - $mustQuery = []; - $mustQuery[] = [ - 'bool' => [ - 'should' => $termQuery, - ], - ]; - - if ($webspaceKey) { - $mustQuery[] = [ - 'bool' => [ - 'should' => [ - [ - 'term' => ['main_webspace' => $webspaceKey], - ], - [ - 'term' => ['additional_webspaces' => $webspaceKey], - ], - ], - ], - ]; - } - - $mustQuery[] = [ - 'more_like_this' => [ - 'like' => [ - [ - '_id' => $uuid . '-' . $locale, - ], - ], - 'fields' => ['title', 'teaser_description'], - 'min_term_freq' => 1, - 'min_doc_freq' => 2, - ], - ]; - - $expectedSearch = [ - 'bool' => [ - 'filter' => [ - [ - 'term' => ['locale' => $locale], - ], - ], - 'must' => $mustQuery, - ], - ]; - - $documentIterator = $this->prophesize(DocumentIterator::class); - - $this->repository->findDocuments(Argument::that(function(Search $search) use ($expectedSearch, $limit) { - $this->assertEquals($expectedSearch, $search->getQueries()->toArray()); - $this->assertEquals($limit, $search->getSize()); - $this->assertCount(0, $search->getSorts()); - - return true; - }))->willReturn($documentIterator->reveal()); - - $this->assertSame( - $documentIterator->reveal(), - $this->articleViewDocumentRepository->findSimilar($uuid, $limit, $types, $locale, $webspaceKey) - ); - } - - /** - * @dataProvider dataProvider - * - * @param string $excludeUuid - * @param string $locale - * @param int $limit - * @param string $webspaceKey - */ - public function testFindRecent( - $excludeUuid = '123-123-123', - array $types = ['blog'], - $locale = 'de', - $limit = 12, - $webspaceKey = null - ) { - $termQuery = []; - foreach ($types as $type) { - $termQuery[] = [ - 'term' => ['type' => $type], - ]; - } - - $expectedSearch = [ - 'bool' => [ - 'filter' => [ - [ - 'term' => ['locale' => $locale], - ], - ], - 'must' => [ - [ - 'bool' => [ - 'should' => $termQuery, - ], - ], - ], - 'must_not' => [ - [ - 'term' => [ - 'uuid' => $excludeUuid, - ], - ], - ], - ], - ]; - - if ($webspaceKey) { - $expectedSearch['bool']['must'][] = [ - 'bool' => [ - 'should' => [ - [ - 'term' => ['main_webspace' => $webspaceKey], - ], - [ - 'term' => ['additional_webspaces' => $webspaceKey], - ], - ], - ], - ]; - } - - $documentIterator = $this->prophesize(DocumentIterator::class); - - $this->repository->findDocuments(Argument::that(function(Search $search) use ($expectedSearch, $limit) { - $this->assertEquals($expectedSearch, $search->getQueries()->toArray()); - $this->assertEquals($limit, $search->getSize()); - $this->assertCount(1, $search->getSorts()); - $this->assertEquals(new FieldSort('authored', FieldSort::DESC), \current($search->getSorts())); - - return true; - }))->willReturn($documentIterator->reveal()); - - $this->assertSame( - $documentIterator->reveal(), - $this->articleViewDocumentRepository->findRecent($excludeUuid, $limit, $types, $locale, $webspaceKey) - ); - } -} diff --git a/Tests/Unit/Routing/ArticlePageRouteGeneratorTest.php b/Tests/Unit/Routing/ArticlePageRouteGeneratorTest.php deleted file mode 100644 index cab98f5bd..000000000 --- a/Tests/Unit/Routing/ArticlePageRouteGeneratorTest.php +++ /dev/null @@ -1,75 +0,0 @@ -routeGenerator = $this->prophesize(RouteGeneratorInterface::class); - $this->tokenProvider = $this->prophesize(TokenProviderInterface::class); - - $this->articleRouteGenerator = new ArticlePageRouteGenerator( - $this->routeGenerator->reveal(), - $this->tokenProvider->reveal() - ); - } - - public function testGenerate() - { - $entity = $this->prophesize(\stdClass::class); - - $parent = '/{object.getParentPath()}'; - $this->tokenProvider->provide($entity->reveal(), 'object.getParentPath()')->willReturn('parent'); - - $this->routeGenerator->generate($entity->reveal(), ['route_schema' => '/parent' . $this->routeSchema]) - ->shouldBeCalled() - ->willReturn('/parent/page-2'); - - $result = $this->articleRouteGenerator->generate( - $entity->reveal(), - ['parent' => $parent, 'route_schema' => $this->routeSchema] - ); - $this->assertEquals('/parent/page-2', $result); - } - - public function testGetOptionsResolver() - { - $this->assertInstanceOf(OptionsResolver::class, $this->articleRouteGenerator->getOptionsResolver([])); - } -} diff --git a/Tests/Unit/Routing/ArticleRouteDefaultProviderTest.php b/Tests/Unit/Routing/ArticleRouteDefaultProviderTest.php deleted file mode 100644 index f80e4a45b..000000000 --- a/Tests/Unit/Routing/ArticleRouteDefaultProviderTest.php +++ /dev/null @@ -1,287 +0,0 @@ -documentManager = $this->prophesize(DocumentManagerInterface::class); - $this->structureMetadataFactory = $this->prophesize(StructureMetadataFactoryInterface::class); - $this->cacheLifetimeResolver = $this->prophesize(CacheLifetimeResolverInterface::class); - $this->structureManager = $this->prophesize(StructureManagerInterface::class); - $this->webspaceResolver = $this->prophesize(WebspaceResolver::class); - $this->requestAnalyzer = $this->prophesize(RequestAnalyzer::class); - - $this->provider = new ArticleRouteDefaultProvider( - $this->documentManager->reveal(), - $this->structureMetadataFactory->reveal(), - $this->cacheLifetimeResolver->reveal(), - $this->structureManager->reveal(), - $this->webspaceResolver->reveal(), - $this->requestAnalyzer->reveal() - ); - } - - public function publishedDataProvider() - { - $articleDocument = new ArticleDocument(); - $articleDocument->setWorkflowStage(WorkflowStage::TEST); - - $articleDocumentPublished = new ArticleDocument(); - $articleDocumentPublished->setWorkflowStage(WorkflowStage::PUBLISHED); - - $unknownDocument = new UnknownDocument(); - - return [ - [$articleDocument, 'test', 'test', [], false], - [$articleDocumentPublished, 'test', 'test', [], true], - [$articleDocumentPublished, 'test', 'other_webspace', ['test', 'one_more_other_webspace'], true], - [$unknownDocument, 'test', null, [], false], - ]; - } - - /** - * @dataProvider publishedDataProvider - */ - public function testIsPublished( - $document, - $webspaceKey, - $documentMainWebspace, - $documentAdditionalWebspaces, - $result - ) { - if ($document instanceof ArticleDocument) { - $this->webspaceResolver->resolveMainWebspace($document)->willReturn($documentMainWebspace); - $this->webspaceResolver->resolveAdditionalWebspaces($document)->willReturn($documentAdditionalWebspaces); - } - - $this->documentManager->find( - $this->entityId, - $this->locale, - [ - 'load_ghost_content' => false, - ] - )->willReturn($document); - - $webspace = $this->prophesize(Webspace::class); - $webspace->getKey()->willReturn($webspaceKey); - - $this->requestAnalyzer->getWebspace()->willReturn($webspace->reveal()); - - $this->assertEquals($result, $this->provider->isPublished($this->entityClass, $this->entityId, $this->locale)); - } - - public function publishedDataProviderWithShadow() - { - $articleDocument = new ArticleDocument(); - $articleDocument->setWorkflowStage(WorkflowStage::TEST); - $articleDocument->setShadowLocale('en'); - $articleDocument->setShadowLocaleEnabled(true); - - $baseDocument = new ArticleDocument(); - $baseDocument->setWorkflowStage(WorkflowStage::TEST); - - $baseDocumentPublished = new ArticleDocument(); - $baseDocumentPublished->setWorkflowStage(WorkflowStage::PUBLISHED); - - $unknownDocument = new UnknownDocument(); - - return [ - [$articleDocument, $baseDocument, false], - [$articleDocument, $baseDocumentPublished, true], - [$articleDocument, $unknownDocument, false], - ]; - } - - /** - * @dataProvider publishedDataProviderWithShadow - */ - public function testIsPublishedWithShadow( - $document, - $baseDocument, - $result - ) { - $webspace = $this->prophesize(Webspace::class); - $webspace->getKey()->willReturn('test'); - - $this->requestAnalyzer->getWebspace()->willReturn($webspace->reveal()); - - if ($document instanceof ArticleDocument) { - $this->webspaceResolver->resolveMainWebspace($baseDocument)->willReturn('test'); - $this->webspaceResolver->resolveAdditionalWebspaces($baseDocument)->willReturn([]); - } - - $this->documentManager->find( - $this->entityId, - $this->locale, - [ - 'load_ghost_content' => false, - ] - )->willReturn($document); - - $this->documentManager->find( - $this->entityId, - 'en', - [ - 'load_ghost_content' => false, - ] - )->willReturn($baseDocument); - - $webspace = $this->prophesize(Webspace::class); - $webspace->getKey()->willReturn('test'); - - $this->requestAnalyzer->getWebspace()->willReturn($webspace->reveal()); - - $this->assertEquals($result, $this->provider->isPublished($this->entityClass, $this->entityId, $this->locale)); - } - - public function testGetByEntity() - { - $article = $this->prophesize(ArticleDocument::class); - $article->getStructureType()->willReturn('default'); - $article->getPageNumber()->willReturn(1); - - $structureMetadata = new StructureMetadata('default'); - $structureMetadata->setView('default.html.twig'); - $structureMetadata->setCacheLifetime(['type' => 'seconds', 'value' => 3600]); - $structureMetadata->setController('Sulu\\Bundle\\ArticleBundle\\Controller\\WebsiteArticleController::indexAction'); - - $this->documentManager->find($this->entityId, $this->locale)->willReturn($article->reveal()); - $this->structureMetadataFactory->getStructureMetadata('article', 'default')->willReturn($structureMetadata); - $this->cacheLifetimeResolver->supports('seconds', 3600)->willReturn(true); - $this->cacheLifetimeResolver->resolve('seconds', 3600)->willReturn(3600); - - $structure = $this->prophesize(ArticleBridge::class); - $structure->setDocument($article->reveal())->shouldBeCalled(); - $this->structureManager->wrapStructure('article', $structureMetadata)->willReturn($structure->reveal()); - - $result = $this->provider->getByEntity($this->entityClass, $this->entityId, $this->locale); - - $this->assertEquals( - [ - 'object' => $article->reveal(), - 'structure' => $structure->reveal(), - 'view' => 'default.html.twig', - 'pageNumber' => 1, - '_controller' => 'Sulu\\Bundle\\ArticleBundle\\Controller\\WebsiteArticleController::indexAction', - '_cacheLifetime' => 3600, - ], - $result - ); - } - - public function testGetByEntityArticlePage() - { - $articlePage = $this->prophesize(ArticlePageDocument::class); - $articlePage->getPageNumber()->willReturn(2); - - $article = $this->prophesize(ArticleDocument::class); - $article->getStructureType()->willReturn('default'); - $article->getPageNumber()->willReturn(1); - $articlePage->getParent()->willReturn($article->reveal()); - - $structureMetadata = new StructureMetadata('default'); - $structureMetadata->setView('default.html.twig'); - $structureMetadata->setCacheLifetime(['type' => 'seconds', 'value' => 3600]); - $structureMetadata->setController('Sulu\\Bundle\\ArticleBundle\\Controller\\WebsiteArticleController::indexAction'); - - $this->documentManager->find($this->entityId, $this->locale)->willReturn($articlePage->reveal()); - $this->structureMetadataFactory->getStructureMetadata('article', 'default')->willReturn($structureMetadata); - $this->cacheLifetimeResolver->supports('seconds', 3600)->willReturn(true); - $this->cacheLifetimeResolver->resolve('seconds', 3600)->willReturn(3600); - - $structure = $this->prophesize(ArticleBridge::class); - $structure->setDocument($article->reveal())->shouldBeCalled(); - $this->structureManager->wrapStructure('article', $structureMetadata)->willReturn($structure->reveal()); - - $result = $this->provider->getByEntity($this->entityClass, $this->entityId, $this->locale); - - $this->assertEquals( - [ - 'object' => $article->reveal(), - 'structure' => $structure->reveal(), - 'view' => 'default.html.twig', - 'pageNumber' => 2, - '_controller' => 'Sulu\\Bundle\\ArticleBundle\\Controller\\WebsiteArticleController::indexAction', - '_cacheLifetime' => 3600, - ], - $result - ); - } -} diff --git a/Tests/Unit/Routing/ArticleRouteEnhancerTest.php b/Tests/Unit/Routing/ArticleRouteEnhancerTest.php deleted file mode 100644 index f5123d50b..000000000 --- a/Tests/Unit/Routing/ArticleRouteEnhancerTest.php +++ /dev/null @@ -1,117 +0,0 @@ -webspace = $this->prophesize(Webspace::class); - $this->webspace->getKey()->willReturn('webspace_key'); - - $this->requestAttributes = $this->prophesize(RequestAttributes::class); - $this->requestAttributes->getAttribute('webspace')->willReturn($this->webspace->reveal()); - - $this->request = $this->prophesize(Request::class); - $this->request->get('_sulu')->willReturn($this->requestAttributes); - - $this->article = $this->prophesize(ArticleDocument::class); - $this->article->getRoutePath()->willReturn('/route/path'); - $this->article->getLocale()->willReturn('locale'); - - $this->defaults['object'] = $this->article->reveal(); - - $this->webspaceManager = $this->prophesize(WebspaceManagerInterface::class); - $this->webspaceManager->findUrlByResourceLocator( - '/route/path', - 'env_value', - 'locale', - 'main_webspace_key' - )->willReturn('main-webspace/route/path'); - - $this->webspaceResolver = $this->prophesize(WebspaceResolver::class); - $this->webspaceResolver->resolveAdditionalWebspaces($this->article)->willReturn(['webspace_key']); - $this->webspaceResolver->resolveMainWebspace($this->article)->willReturn('main_webspace_key'); - - $this->articleRouteGenerator = new ArticleRouteEnhancer( - $this->webspaceManager->reveal(), - $this->webspaceResolver->reveal(), - 'env_value' - ); - } - - public function testEnhance() - { - $defaults = $this->articleRouteGenerator->enhance($this->defaults, $this->request->reveal()); - $this->assertArrayHasKey('_seo', $defaults); - $this->assertTrue(\is_array($defaults['_seo'])); - $this->assertArrayHasKey('canonicalUrl', $defaults['_seo']); - $this->assertEquals('main-webspace/route/path', $defaults['_seo']['canonicalUrl']); - } - - public function testEnhanceInvalidOne() - { - $this->webspaceResolver->resolveAdditionalWebspaces($this->article)->willReturn(['another_webspace_key']); - - $defaults = $this->articleRouteGenerator->enhance($this->defaults, $this->request->reveal()); - $this->assertArrayNotHasKey('_seo', $defaults); - } -} diff --git a/Tests/Unit/Routing/ArticleRouteGeneratorByTemplateTest.php b/Tests/Unit/Routing/ArticleRouteGeneratorByTemplateTest.php deleted file mode 100644 index 5ef3ad44c..000000000 --- a/Tests/Unit/Routing/ArticleRouteGeneratorByTemplateTest.php +++ /dev/null @@ -1,60 +0,0 @@ - '/test1/{entity.getTitle()', 'test2' => '/test2/{entity.getTitle()']; - - public function setUp(): void - { - $this->generatorBySchema = $this->prophesize(RouteGeneratorInterface::class); - $this->generatorByTemplate = new ArticleRouteGeneratorByTemplate($this->generatorBySchema->reveal()); - } - - public function testGenerate() - { - $entity = $this->prophesize(StructureBehavior::class); - $entity->getStructureType()->willReturn('test1'); - - $this->generatorByTemplate->generate($entity->reveal(), $this->config); - - $this->generatorBySchema->generate($entity->reveal(), ['route_schema' => '/test1/{entity.getTitle()']) - ->shouldBeCalled(); - } - - public function testGenerateNotConfigured() - { - $this->expectException(RouteSchemaNotFoundException::class); - - $entity = $this->prophesize(StructureBehavior::class); - $entity->getStructureType()->willReturn('test3'); - - $this->generatorByTemplate->generate($entity->reveal(), $this->config); - } -} diff --git a/Tests/Unit/Routing/ArticleRouteGeneratorByTypeTest.php b/Tests/Unit/Routing/ArticleRouteGeneratorByTypeTest.php deleted file mode 100644 index 32b3b3c3b..000000000 --- a/Tests/Unit/Routing/ArticleRouteGeneratorByTypeTest.php +++ /dev/null @@ -1,89 +0,0 @@ - '/test1/{entity.getTitle()', 'type2' => '/test2/{entity.getTitle()']; - - public function setUp(): void - { - $this->generatorBySchema = $this->prophesize(RouteGeneratorInterface::class); - $this->structureMetadataFactory = $this->prophesize(StructureMetadataFactoryInterface::class); - - $this->generatorByTemplate = new ArticleRouteGeneratorByType( - $this->generatorBySchema->reveal(), - $this->structureMetadataFactory->reveal() - ); - } - - public function testGenerate() - { - $metadata = new StructureMetadata(); - $metadata->setTags([ - ['name' => 'sulu_article.type', 'attributes' => ['type' => 'type1']], - ]); - - $this->structureMetadataFactory->getStructureMetadata('article', 'test1')->willReturn($metadata); - - $entity = $this->prophesize(StructureBehavior::class); - $entity->getStructureType()->willReturn('test1'); - - $this->generatorByTemplate->generate($entity->reveal(), $this->config); - - $this->generatorBySchema->generate($entity->reveal(), ['route_schema' => '/test1/{entity.getTitle()']) - ->shouldBeCalled(); - } - - public function testGenerateNotConfigured() - { - $this->expectException(RouteSchemaNotFoundException::class); - - $metadata = new StructureMetadata(); - $metadata->setTags([ - ['name' => 'sulu_article.type', 'attributes' => ['type' => 'type3']], - ]); - - $this->structureMetadataFactory->getStructureMetadata('article', 'test3')->willReturn($metadata); - - $entity = $this->prophesize(StructureBehavior::class); - $entity->getStructureType()->willReturn('test3'); - - $this->generatorByTemplate->generate($entity->reveal(), $this->config); - } -} diff --git a/Tests/Unit/Twig/ArticleViewDocumentTwigExtensionTest.php b/Tests/Unit/Twig/ArticleViewDocumentTwigExtensionTest.php deleted file mode 100644 index ca2178d3b..000000000 --- a/Tests/Unit/Twig/ArticleViewDocumentTwigExtensionTest.php +++ /dev/null @@ -1,239 +0,0 @@ -getArticleDocuments(); - $articleViewDocuments = $this->getArticleViewDocuments($articleDocuments); - $articleResourceItems = $this->getArticleResourceItems($articleDocuments, $articleViewDocuments); - $documentIterator = $this->getDocumentIterator($articleViewDocuments); - $metadataFactory = $this->getMetadataFactory(); - - $articleViewDocumentRepository = $this->prophesize(ArticleViewDocumentRepository::class); - $articleViewDocumentRepository->findSimilar( - $articleDocuments[0]->getUuid(), - 5, - [ - $articleDocuments[0]->getStructureType(), - ], - $articleDocuments[0]->getLocale(), - 'webspace_key' - )->willReturn($documentIterator); - - $articleResourceItemFactory = $this->prophesize(ArticleResourceItemFactory::class); - $articleResourceItemFactory->createResourceItem($articleViewDocuments[1])->willReturn($articleResourceItems[1]); - $articleResourceItemFactory->createResourceItem($articleViewDocuments[2])->willReturn($articleResourceItems[2]); - - $webspace = $this->prophesize(Webspace::class); - $webspace->getKey()->willReturn('webspace_key'); - - $requestAttributes = $this->prophesize(RequestAttributes::class); - $requestAttributes->getAttribute('webspace')->willReturn($webspace->reveal()); - - $request = $this->prophesize(Request::class); - $request->get('object')->willReturn($articleDocuments[0]); - $request->getLocale()->willReturn('de'); - $request->get('_sulu')->willReturn($requestAttributes->reveal()); - - $requestStack = $this->prophesize(RequestStack::class); - $requestStack->getCurrentRequest()->willReturn($request->reveal()); - - $referenceStore = $this->prophesize(ReferenceStore::class); - $referenceStore->add($articleDocuments[1]->getUuid())->shouldBeCalled(); - $referenceStore->add($articleDocuments[2]->getUuid())->shouldBeCalled(); - - $extension = new ArticleViewDocumentTwigExtension( - $articleViewDocumentRepository->reveal(), - $articleResourceItemFactory->reveal(), - $referenceStore->reveal(), - $metadataFactory->reveal(), - $requestStack->reveal() - ); - - $this->assertEquals( - [ - $articleResourceItems[1], - $articleResourceItems[2], - ], - $extension->loadSimilar() - ); - } - - public function testFindRecent() - { - $articleDocuments = $this->getArticleDocuments(); - $articleViewDocuments = $this->getArticleViewDocuments($articleDocuments); - $articleResourceItems = $this->getArticleResourceItems($articleDocuments, $articleViewDocuments); - $documentIterator = $this->getDocumentIterator($articleViewDocuments); - $metadataFactory = $this->getMetadataFactory(); - - $articleViewDocumentRepository = $this->prophesize(ArticleViewDocumentRepository::class); - $articleViewDocumentRepository->findRecent( - $articleDocuments[0]->getUuid(), - 5, - [ - $articleDocuments[0]->getStructureType(), - ], - $articleDocuments[0]->getLocale(), - 'webspace_key' - )->willReturn($documentIterator); - - $articleResourceItemFactory = $this->prophesize(ArticleResourceItemFactory::class); - $articleResourceItemFactory->createResourceItem($articleViewDocuments[1])->willReturn($articleResourceItems[1]); - $articleResourceItemFactory->createResourceItem($articleViewDocuments[2])->willReturn($articleResourceItems[2]); - - $webspace = $this->prophesize(Webspace::class); - $webspace->getKey()->willReturn('webspace_key'); - - $requestAttributes = $this->prophesize(RequestAttributes::class); - $requestAttributes->getAttribute('webspace')->willReturn($webspace->reveal()); - - $request = $this->prophesize(Request::class); - $request->get('object')->willReturn($articleDocuments[0]); - $request->getLocale()->willReturn('de'); - $request->get('_sulu')->willReturn($requestAttributes->reveal()); - - $requestStack = $this->prophesize(RequestStack::class); - $requestStack->getCurrentRequest()->willReturn($request->reveal()); - - $referenceStore = $this->prophesize(ReferenceStore::class); - $referenceStore->add($articleDocuments[1]->getUuid())->shouldBeCalled(); - $referenceStore->add($articleDocuments[2]->getUuid())->shouldBeCalled(); - - $extension = new ArticleViewDocumentTwigExtension( - $articleViewDocumentRepository->reveal(), - $articleResourceItemFactory->reveal(), - $referenceStore->reveal(), - $metadataFactory->reveal(), - $requestStack->reveal() - ); - - $this->assertEquals( - [ - $articleResourceItems[1], - $articleResourceItems[2], - ], - $extension->loadRecent() - ); - } - - /** - * @return MetadataFactory - */ - private function getMetadataFactory() - { - $metadata = new StructureMetadata(); - $metadata->setTags([ - ['name' => 'sulu_article.type', 'attributes' => ['type' => 'blog']], - ]); - - $metadataFactory = $this->prophesize(StructureMetadataFactory::class); - $metadataFactory->getStructureMetadata('article', 'blog')->willReturn($metadata); - - return $metadataFactory; - } - - /** - * @return array - */ - private function getArticleDocuments() - { - $ids = ['123-123-123', '321-321-321', '111-111-111']; - - return \array_map( - function($id) { - $articleDocument = new ArticleDocument(); - $articleDocument->setUuid($id); - $articleDocument->setLocale('de'); - $articleDocument->setStructureType('blog'); - - return $articleDocument; - }, - \array_values($ids) - ); - } - - /** - * @return array - */ - private function getArticleViewDocuments(array $articleDocuments) - { - return \array_map( - function($articleDocument) { - $articleViewDocument = new ArticleViewDocument($articleDocument->getUuid()); - $articleViewDocument->setLocale($articleDocument->getLocale()); - $articleViewDocument->setStructureType($articleDocument->getStructureType()); - - return $articleViewDocument; - }, - \array_values($articleDocuments) - ); - } - - /** - * @return array - */ - private function getArticleResourceItems(array $articleDocuments, array $articleViewDocuments) - { - $articleResourceItems = []; - - foreach ($articleViewDocuments as $key => $value) { - $articleResourceItems[] = new ArticleResourceItem($articleViewDocuments[$key], $articleDocuments[$key]); - } - - return $articleResourceItems; - } - - /** - * @return DocumentIterator - */ - private function getDocumentIterator(array $articleViewDocuments) - { - $documentIteratorCount = 1; - - $documentIterator = $this->prophesize(DocumentIterator::class); - $documentIterator->rewind()->willReturn(0); - $documentIterator->next()->willReturn($documentIteratorCount); - $documentIterator->current()->will(function() use (&$documentIteratorCount, $articleViewDocuments) { - return $articleViewDocuments[$documentIteratorCount++]; - }); - $documentIterator->valid()->will(function() use (&$documentIteratorCount, $articleViewDocuments) { - if (\array_key_exists($documentIteratorCount, $articleViewDocuments)) { - return true; - } - - return false; - }); - - return $documentIterator; - } -} diff --git a/Trash/ArticleTrashItemHandler.php b/Trash/ArticleTrashItemHandler.php deleted file mode 100644 index 23a9bf095..000000000 --- a/Trash/ArticleTrashItemHandler.php +++ /dev/null @@ -1,221 +0,0 @@ -trashItemRepository = $trashItemRepository; - $this->documentManager = $documentManager; - $this->documentInspector = $documentInspector; - $this->documentDomainEventCollector = $documentDomainEventCollector; - } - - /** - * @param ArticleDocument $article - */ - public function store(object $article, array $options = []): TrashItemInterface - { - Assert::isInstanceOf($article, ArticleDocument::class); - - $articleTitles = []; - $data = [ - 'parentUuid' => $article->getParent()->getUuid(), - 'locales' => [], - ]; - - $restoreType = isset($options['locale']) ? 'translation' : null; - $locales = isset($options['locale']) ? [$options['locale']] : $this->documentInspector->getLocales($article); - - /** @var string $locale */ - foreach ($locales as $locale) { - /** @var ArticleDocument $localizedArticle */ - $localizedArticle = $this->documentManager->find($article->getUuid(), $locale); - - $extensionsData = ($localizedArticle->getExtensionsData() instanceof ExtensionContainer) - ? $localizedArticle->getExtensionsData()->toArray() - : $localizedArticle->getExtensionsData(); - - // routePath property of structure contains route of target locale in case of a shadow page - // we want to restore the path of the source locale, therefore we use the value of the document - $structureData = $localizedArticle->getStructure()->toArray(); - - $articleTitles[$locale] = $localizedArticle->getTitle(); - $lastModified = $localizedArticle->getLastModified() ? $localizedArticle->getLastModified()->format('c') : null; - - $data['locales'][] = [ - 'title' => $localizedArticle->getTitle(), - 'locale' => $locale, - 'creator' => $localizedArticle->getCreator(), - 'created' => $localizedArticle->getCreated()->format('c'), - 'lastModified' => $lastModified, - 'author' => $localizedArticle->getAuthor(), - 'authored' => $localizedArticle->getAuthored()->format('c'), - 'structureType' => $localizedArticle->getStructureType(), - 'structureData' => $structureData, - 'extensionsData' => $extensionsData, - 'shadowLocaleEnabled' => $localizedArticle->isShadowLocaleEnabled(), - 'shadowLocale' => $localizedArticle->getShadowLocale(), - 'mainWebspace' => $localizedArticle->getMainWebspace(), - 'additionalWebspaces' => $localizedArticle->getAdditionalWebspaces(), - ]; - } - - return $this->trashItemRepository->create( - ArticleDocument::RESOURCE_KEY, - (string) $article->getUuid(), - $articleTitles, - $data, - $restoreType, - $options, - ArticleAdmin::SECURITY_CONTEXT, - null, - null - ); - } - - public function restore(TrashItemInterface $trashItem, array $restoreFormData = []): object - { - $uuid = $trashItem->getResourceId(); - $data = $trashItem->getRestoreData(); - $localizedArticle = null; - - // restore shadow locales after concrete locales because shadow locales depend on their target locale - $sortedLocales = []; - foreach ($data['locales'] as $localeData) { - if ($localeData['shadowLocaleEnabled']) { - $sortedLocales[] = $localeData; - } else { - \array_unshift($sortedLocales, $localeData); - } - } - - /** @var array{ - * title: string, - * locale: string, - * creator: ?int, - * created: string, - * lastModified: ?string, - * author: ?int, - * authored: string, - * structureType: string, - * structureData: mixed, - * extensionsData: mixed, - * shadowLocaleEnabled: bool, - * shadowLocale: ?string, - * mainWebspace: ?string, - * additionalWebspaces: ?array, - * } $localeData - */ - foreach ($sortedLocales as $localeData) { - $locale = $localeData['locale']; - - try { - /** @var ArticleDocument $localizedArticle */ - $localizedArticle = $this->documentManager->find($uuid, $locale, ['load_ghost_content' => false]); - } catch (DocumentNotFoundException $exception) { - /** @var ArticleDocument $localizedArticle */ - $localizedArticle = $this->documentManager->create(ArticleController::DOCUMENT_TYPE); - $localizedArticle->setParent($this->documentManager->find($data['parentUuid'])); - $localizedArticle->setUuid($uuid); - } - $lastModified = \array_key_exists('lastModified', $localeData) && $localeData['lastModified'] ? new \DateTime($localeData['lastModified']) : null; - - $localizedArticle->setTitle($localeData['title']); - $localizedArticle->setLocale($locale); - $localizedArticle->setCreator($localeData['creator']); - $localizedArticle->setCreated(new \DateTime($localeData['created'])); - $localizedArticle->setLastModified($lastModified); - $localizedArticle->setAuthor($localeData['author']); - $localizedArticle->setAuthored(new \DateTime($localeData['authored'])); - $localizedArticle->setStructureType($localeData['structureType']); - $localizedArticle->getStructure()->bind($localeData['structureData']); - $localizedArticle->setExtensionsData($localeData['extensionsData']); - $localizedArticle->setShadowLocaleEnabled($localeData['shadowLocaleEnabled']); - $localizedArticle->setShadowLocale($localeData['shadowLocale']); - $localizedArticle->setMainWebspace($localeData['mainWebspace']); - $localizedArticle->setAdditionalWebspaces($localeData['additionalWebspaces']); - - $this->documentManager->persist($localizedArticle, $locale, ['omit_modified_domain_event' => true]); - } - - Assert::isInstanceOf($localizedArticle, ArticleDocument::class); - $event = 'translation' === $trashItem->getRestoreType() - ? new ArticleTranslationRestoredEvent($localizedArticle, $trashItem->getRestoreOptions()['locale'], $data) - : new ArticleRestoredEvent($localizedArticle, $data); - $this->documentDomainEventCollector->collect($event); - $this->documentManager->flush(); - - return $localizedArticle; - } - - public static function getResourceKey(): string - { - return ArticleDocument::RESOURCE_KEY; - } - - public function getConfiguration(): RestoreConfiguration - { - return new RestoreConfiguration( - null, - ArticleAdmin::LIST_VIEW, - ); - } -} diff --git a/Twig/ArticleViewDocumentTwigExtension.php b/Twig/ArticleViewDocumentTwigExtension.php deleted file mode 100644 index 761cc0282..000000000 --- a/Twig/ArticleViewDocumentTwigExtension.php +++ /dev/null @@ -1,228 +0,0 @@ -articleViewDocumentRepository = $articleViewDocumentRepository; - $this->articleResourceItemFactory = $articleResourceItemFactory; - $this->referenceStore = $referenceStore; - $this->structureMetadataFactory = $structureMetadataFactory; - $this->requestStack = $requestStack; - } - - /** - * {@inheritdoc} - * - * Returns an array of possible function in this extension. - */ - public function getFunctions() - { - return [ - new TwigFunction('sulu_article_load_recent', [$this, 'loadRecent']), - new TwigFunction('sulu_article_load_similar', [$this, 'loadSimilar']), - ]; - } - - /** - * Loads recent articles with given parameters. - * - * @return ArticleResourceItem[] - */ - public function loadRecent( - int $limit = ArticleViewDocumentRepository::DEFAULT_LIMIT, - ?array $types = null, - ?string $locale = null, - bool $ignoreWebspaces = false - ): array { - $excludeUuid = null; - - /** @var Request $request */ - $request = $this->requestStack->getCurrentRequest(); - - $articleDocument = $request->get('object'); - if ($articleDocument instanceof ArticleDocument) { - $excludeUuid = $articleDocument->getUuid(); - - if (!$types) { - $types = [$this->getArticleType($articleDocument)]; - } - } - - if (!$locale) { - $locale = $request->getLocale(); - } - - $webspaceKey = $this->getWebspaceKey($request, $ignoreWebspaces); - - $articleViewDocuments = $this->articleViewDocumentRepository->findRecent( - $excludeUuid, - $limit, - $types, - $locale, - $webspaceKey - ); - - return $this->getResourceItems($articleViewDocuments); - } - - /** - * Loads similar articles with given parameters. - * - * @return ArticleResourceItem[] - * - * @throws ArticleInRequestNotFoundException - */ - public function loadSimilar( - int $limit = ArticleViewDocumentRepository::DEFAULT_LIMIT, - ?array $types = null, - ?string $locale = null, - bool $ignoreWebspaces = false - ): array { - $uuid = null; - - $request = $this->requestStack->getCurrentRequest(); - - $articleDocument = $request->get('object'); - if ($articleDocument instanceof ArticleDocument) { - $uuid = $articleDocument->getUuid(); - - if (!$types) { - $types = [$this->getArticleType($articleDocument)]; - } - } - - if (!$uuid) { - throw new ArticleInRequestNotFoundException(); - } - - if (!$locale) { - $locale = $request->getLocale(); - } - - $webspaceKey = $this->getWebspaceKey($request, $ignoreWebspaces); - - $articleViewDocuments = $this->articleViewDocumentRepository->findSimilar( - $uuid, - $limit, - $types, - $locale, - $webspaceKey - ); - - return $this->getResourceItems($articleViewDocuments); - } - - public function getName(): string - { - return 'sulu_article.article_view_document'; - } - - /** - * @return ArticleResourceItem[] - */ - private function getResourceItems(DocumentIterator $articleViewDocuments): array - { - $articleResourceItems = []; - - /** @var ArticleViewDocument $articleViewDocument */ - foreach ($articleViewDocuments as $articleViewDocument) { - $this->referenceStore->add($articleViewDocument->getUuid()); - $articleResourceItems[] = $this->articleResourceItemFactory->createResourceItem($articleViewDocument); - } - - return $articleResourceItems; - } - - private function getArticleType(ArticleDocument $articleDocument): string - { - $structureMetadata = $this->structureMetadataFactory->getStructureMetadata( - 'article', - $articleDocument->getStructureType() - ); - - return $this->getType($structureMetadata); - } - - private function getWebspaceKey(Request $request, bool $ignoreWebspaces): ?string - { - if ($ignoreWebspaces) { - return null; - } - - $sulu = $request->get('_sulu'); - if (!$sulu) { - return null; - } - - /** @var Webspace $webspace */ - $webspace = $sulu->getAttribute('webspace'); - if (!$webspace) { - return null; - } - - return $webspace->getKey(); - } -} diff --git a/Resources/translations/admin.de.json b/translations/admin.de.json similarity index 100% rename from Resources/translations/admin.de.json rename to translations/admin.de.json diff --git a/Resources/translations/admin.en.json b/translations/admin.en.json similarity index 100% rename from Resources/translations/admin.en.json rename to translations/admin.en.json