diff --git a/cms/contents/page/translations/sfs_cms_contents.en.yaml b/cms/contents/page/translations/sfs_cms_contents.en.yaml index 2de01197..5aa69287 100644 --- a/cms/contents/page/translations/sfs_cms_contents.en.yaml +++ b/cms/contents/page/translations/sfs_cms_contents.en.yaml @@ -52,29 +52,6 @@ admin_page: confirm_message_title: "Unpublish page" confirm_message_raw: "

Are you sure to unpublish this page?

It will show a 404 error to the users

" - import: - meta.title: "Import page" - title: "Import page" - breadcrumb: "Import page" - actions: - import.button: "Import page" - cancel.button: "Cancel" - form: - file.label: "Import content file" - failed_flash: "An error has been produced during the page import
%exception%" - duplicated_flash: "An error has been produced during the page import, the page already exists in the database, try to import it as a version
%exception%" - success_flash: "Page has been imported" - - import_version: - meta.title: "Import version" - title: "Import version" - breadcrumb: "Import version" - actions: - import.button: "Import version" - cancel.button: "Cancel" - form: - file.label: "Import content file" - read: meta.title: "General" title: "%name%" @@ -135,8 +112,6 @@ admin_page: origin: "null": "" 1: "edited" - 2: "fixture" - 3: "imported" 4: "translated" 5: "seo" 6: "duplicated" @@ -145,12 +120,10 @@ admin_page: actions: edit.link: "Edit" preview.link: "Preview" - export.link: "Export" publish.link: "Publish" unpublish: link: "Unpublish" confirm: "Are you sure you want to unpublish this page? It will show a 404 error to the users." - import_version.link: "Import version" cleanup_versions: link: "Cleanup versions" confirm: "Are you sure to cleanup versions? This action will delete all versions except the published one, the last one and the ones marked to keep." @@ -200,7 +173,6 @@ admin_page: offer_backup: 'If you want, you can backup this content published version before deleting' index_warnings_raw: '

Do not lose links and index!

' actions: - export.button: Export delete.button: "Delete definitely" cancel.button: "Cancel" form: @@ -251,7 +223,6 @@ admin_page: breadcrumb: "Pages" actions: create.link: "New page" - import.link: "Import page" details.link: "View" content.link: "Content" preview.link: "Preview" @@ -267,7 +238,7 @@ admin_page: status.label: "Status" publishedVersionContent.label: "Published version content (case sensitive)" empty: - create_first_content_raw: 'Create or import your first page!' + create_first_content_raw: 'Create your first page!' can_not_create_content: "You can not create a new page" go_to_doc_raw: 'If you need help go to documentation' clean_filters: 'Your query has no results, try to clean filters' @@ -323,13 +294,6 @@ admin_page: success_unlocked_flash: "Version has been unlocked" failed_flash: "An error has been produced during the version lock/unlock
%exception%" - version_export: - failed_flash: "An error has been produced during the version export
%exception%" - - version_import: - success_flash: "Version has been imported" - failed_flash: "An error has been produced during the version import
%exception%" - version_cleanup: success_flash: "Versions cleanup has been done correctly" diff --git a/cms/contents/page/translations/sfs_cms_contents.es.yaml b/cms/contents/page/translations/sfs_cms_contents.es.yaml index cd2498be..47f0eee5 100644 --- a/cms/contents/page/translations/sfs_cms_contents.es.yaml +++ b/cms/contents/page/translations/sfs_cms_contents.es.yaml @@ -52,29 +52,6 @@ admin_page: confirm_message_title: "Despublicar página" confirm_message_raw: "

¿Estás seguro de despublicar esta página?

Mostrará un error 404 a los usuarios

" - import: - meta.title: "Importar página" - title: "Importar página" - breadcrumb: "Importar página" - actions: - import.button: "Importar página" - cancel.button: "Cancelar" - form: - file.label: "Fichero a importar" - failed_flash: "Se ha producido un error al importar la página
%exception%" - duplicated_flash: "Se ha producido un error al importar la página, la página ya existe en la base de datos, intenta importarla como versión
%exception%" - success_flash: "La página se ha importado" - - import_version: - meta.title: "Importar versión" - title: "Importar versión" - breadcrumb: "Importar versión" - actions: - import.button: "Importar versión" - cancel.button: "Cancelar" - form: - file.label: "Fichero a importar" - read: meta.title: "General" title: "%name%" @@ -135,8 +112,6 @@ admin_page: origin: "null": "" 1: "editado" - 2: "fixture" - 3: "cargada" 4: "traducida" 5: "seo" 6: "duplicada" @@ -145,12 +120,10 @@ admin_page: actions: edit.link: "Editar" preview.link: "Previsualizar" - export.link: "Exportar" publish.link: "Publicar" unpublish: link: "Despublicar" confirm: "¿Estás seguro de despublicar esta versión? Mostrará un error 404 a los usuarios." - import_version.link: "Importar versión" cleanup_versions: link: "Limpiar versiones" confirm: "¿Estás seguro de limpiar las versiones? Esta acción eliminará todas las versiones excepto la publicada, la última y las marcadas para mantener." @@ -200,7 +173,6 @@ admin_page: offer_backup: 'Si quieres puedes hacer un backup de la versión publicada de este contenido antes' index_warnings_raw: '

¡No pierdas los enlaces e indexación!

' actions: - export.button: "Exportar" delete.button: "Eliminar definitivamente" cancel.button: "Cancelar" form: @@ -251,7 +223,6 @@ admin_page: breadcrumb: "Páginas" actions: create.link: "Nueva página" - import.link: "Importar página" details.link: "Ver" content.link: "Contenido" preview.link: "Previsualizar" @@ -267,7 +238,7 @@ admin_page: status.label: "Estado" publishedVersionContent.label: "Contenido publicado (distingue mayúsculas y minúsculas)" empty: - create_first_content_raw: 'Crea o importa tu primera página!' + create_first_content_raw: 'Crea tu primera página!' can_not_create_content: "No puedes crear páginas" go_to_doc_raw: 'Si necesitas ayuda visita la documentación' clean_filters: 'No se han encontrado páginas con tu búsqueda, limpia los filtros para ver todas las páginas' @@ -323,13 +294,6 @@ admin_page: success_unlocked_flash: "La versión se ha desbloqueado" failed_flash: "Se ha producido un error al bloquear/desbloquear la versión
%exception%" - version_export: - failed_flash: "Se ha producido un error al exportar la versión
%exception%" - - version_import: - success_flash: "La versión se ha importado" - failed_flash: "Se ha producido un error al importar la versión
%exception%" - version_cleanup: success_flash: "Se ha realizado la limpieza de versiones correctamente" @@ -396,7 +360,6 @@ admin_page: main_warnings_raw: '

¿Estás seguro de eliminar esta versión v%versionNumber%?

Esta acción no se podrá deshacer.

' offer_backup: 'Si quieres puedes hacer un backup de la versión antes de eliminarla' actions: - export.button: "Exportar" delete.button: "Eliminar definitivamente" cancel.button: "Cancelar" success_flash: "La versión se ha eliminado" diff --git a/composer.json b/composer.json index 76adc108..3faebf73 100644 --- a/composer.json +++ b/composer.json @@ -54,6 +54,7 @@ }, "suggest": { "softspring/cms-blog-plugin": "Provides a blog for the CMS", + "softspring/cms-data-plugin": "Import/export and fixtures features are now in this plugin. Provides features for the CMS", "softspring/cms-module-coolection": "Provides a module collection for the CMS", "softspring/cms-sections-plugin": "Provides editable sections for the CMS", "softspring/cms-sylius-bundle": "Provides a Sylius integration for the CMS", diff --git a/config/routing/admin_content_type.yaml b/config/routing/admin_content_type.yaml index a322ffe1..a18758e5 100644 --- a/config/routing/admin_content_type.yaml +++ b/config/routing/admin_content_type.yaml @@ -6,15 +6,9 @@ create: controller: sfs_cms.admin.content.controller::create path: /create -import: - controller: sfs_cms.admin.content.controller::create - path: /import - defaults: - configKey: 'import' - details: controller: sfs_cms.admin.content.controller::read - path: /{content} + path: /{content}/details update: controller: sfs_cms.admin.content.controller::update @@ -110,24 +104,12 @@ publish_version: defaults: configKey: 'version_publish' -export_version: - controller: sfs_cms.admin.content_version.controller::apply - path: /{content}/{version}/export - defaults: - configKey: 'version_export' - version_info: controller: sfs_cms.admin.content_version.controller::update path: /{content}/{version}/info defaults: configKey: 'version_info' -import_version: - controller: sfs_cms.admin.content_version.controller::create - path: /{content}/import - defaults: - configKey: 'version_import' - cleanup_versions: controller: sfs_cms.admin.content_version.controller::apply path: /{content}/versions-cleanup diff --git a/config/services/controller/admin_content.yaml b/config/services/controller/admin_content.yaml index d67eb4bb..2c47d62c 100644 --- a/config/services/controller/admin_content.yaml +++ b/config/services/controller/admin_content.yaml @@ -32,18 +32,6 @@ services: form_invalid_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_CREATE_FORM_INVALID view_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_CREATE_VIEW exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_CREATE_EXCEPTION - import: - initialize_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_INITIALIZE - create_entity_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_ENTITY - form_prepare_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_PREPARE - form_init_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_INIT - form_valid_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_VALID - apply_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_APPLY - success_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_SUCCESS - failure_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FAILURE - form_invalid_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_INVALID - view_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_VIEW - exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_IMPORT_EXCEPTION read: param_converter_key: 'id' initialize_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_READ_INITIALIZE @@ -143,4 +131,4 @@ services: not_found_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_DIFF_NOT_FOUND found_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_DIFF_FOUND view_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_DIFF_VIEW - exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_DIFF_EXCEPTION \ No newline at end of file + exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENTS_DIFF_EXCEPTION diff --git a/config/services/controller/admin_content_version.yaml b/config/services/controller/admin_content_version.yaml index 830693d7..3a47e008 100644 --- a/config/services/controller/admin_content_version.yaml +++ b/config/services/controller/admin_content_version.yaml @@ -34,18 +34,6 @@ services: form_invalid_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_CREATE_FORM_INVALID view_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_CREATE_VIEW exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_CREATE_EXCEPTION - version_import: - initialize_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_INITIALIZE - create_entity_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_ENTITY - form_prepare_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_PREPARE - form_init_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_INIT - form_valid_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_VALID - apply_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_APPLY - success_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_SUCCESS - failure_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FAILURE - form_invalid_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_INVALID - view_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_VIEW - exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_EXCEPTION version_preview: param_converter_key: 'id' initialize_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_PREVIEW_INITIALIZE @@ -83,16 +71,6 @@ services: success_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_PUBLISH_SUCCESS failure_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_PUBLISH_FAILURE exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_PUBLISH_EXCEPTION - version_export: - param_converter_key: 'id' - initialize_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_INITIALIZE - load_entity_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_LOAD_ENTITY - not_found_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_NOT_FOUND - found_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_FOUND - apply_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_APPLY - success_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_SUCCESS - failure_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_FAILURE - exception_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_EXCEPTION version_list: initialize_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_LIST_INITIALIZE filter_form_prepare_event_name: !php/const Softspring\CmsBundle\SfsCmsEvents::ADMIN_CONTENT_VERSIONS_LIST_FILTER_FORM_PREPARE diff --git a/config/services/services.yaml b/config/services/services.yaml index 1cd3ef02..1306935a 100644 --- a/config/services/services.yaml +++ b/config/services/services.yaml @@ -15,8 +15,6 @@ services: $esi: '@?esi' $siteConfig: '%sfs_cms.site_config%' $profiler: '@?profiler' - $entityTransformers: !tagged_iterator { tag: sfs_cms.data.entity_transformer, default_priority_method: getPriority } - $fieldTransformers: !tagged_iterator { tag: sfs_cms.data.field_transformer, default_priority_method: getPriority } $cmsLogger: '@?monolog.logger.cms' $debug: '%kernel.debug%' $defaultRestrictPatterns: '%sfs_cms.form_type.symfony_route.default_restrict_patterns%' @@ -27,7 +25,6 @@ services: $contentCacheType: '%sfs_cms.content.cache.type%' $menuCacheType: '%sfs_cms.menu.cache.type%' $blockCacheType: '%sfs_cms.block.cache.type%' - $mediaStoragePath: '%sfs_media.storage.filesystem.path%' $compiledDataExpirationTtl: '%sfs_cms.compiled.expiration_ttl%' $contentRecompileEnabled: '%sfs_cms.content.recompile_enabled%' $registeredPlugins: '%sfs_cms.registered_plugins%' @@ -49,14 +46,6 @@ services: resource: '../../src/Controller/*' tags: [ 'controller.service_arguments' ] - Softspring\CmsBundle\DataFixtures\: - resource: '../../src/DataFixtures/*' - tags: [ 'doctrine.fixtures.loader' ] - - Softspring\CmsBundle\DataFixtures\Purger\CmsPurgerFactory: - tags: - - { name: 'doctrine.fixtures.purger_factory', alias: 'cms_purge' } - Softspring\CmsBundle\Form\Admin\: resource: '../../src/Form/Admin/*' tags: [ 'form.type' ] @@ -77,9 +66,6 @@ services: Softspring\CmsBundle\EventListener\ErrorPageListener: ~ - Softspring\CmsBundle\Data\: - resource: '../../src/Data/*' - Softspring\CmsBundle\Helper\: resource: '../../src/Helper/*' diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 522ae19b..ff3e3277 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -15,9 +15,6 @@ parameters: message: "#Class Softspring\\\\CmsBundle\\\\DataCollector\\\\TwigDataCollector extends @final class Symfony\\\\Bridge\\\\Twig\\\\DataCollector\\\\TwigDataCollector.#" count: 1 path: src/DataCollector/TwigDataCollector.php - - - message: "##" - path: src/DataFixtures/Purger/CmsPurger.php - message: "#Function twig_template_from_string not found.#" reportUnmatched: false diff --git a/src/Admin/ActionListener/Content/ImportListener.php b/src/Admin/ActionListener/Content/ImportListener.php deleted file mode 100644 index 2f577f9d..00000000 --- a/src/Admin/ActionListener/Content/ImportListener.php +++ /dev/null @@ -1,175 +0,0 @@ - [ - ['onInitializeGetConfig', 20], - ['onEventDispatchContentTypeEvent', 10], - ['onInitializeUpdateHelperConfig', 0], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_ENTITY => [ - ['onEventDispatchContentTypeEvent', 10], - ['onCreateEntity', 1], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_PREPARE => [ - ['onEventDispatchContentTypeEvent', 10], - ['onFormPrepareResolve', 0], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_INIT => [ - ['onEventDispatchContentTypeEvent', 10], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_VALID => [ - ['onEventDispatchContentTypeEvent', 10], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_APPLY => [ - ['onEventDispatchContentTypeEvent', 10], - ['onApply', 0], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_SUCCESS => [ - ['onEventDispatchContentTypeEvent', 10], - ['onSuccess', 0], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FAILURE => [ - ['onEventDispatchContentTypeEvent', 10], - ['onFailure', 0], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_FORM_INVALID => [ - ['onEventDispatchContentTypeEvent', 10], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_VIEW => [ - ['onEventDispatchContentTypeEvent', 10], - ['onViewAddConfig', 0], - ['onViewSetTemplate', 0], - ['onViewAddEntities', 0], - ], - SfsCmsEvents::ADMIN_CONTENTS_IMPORT_EXCEPTION => [ - ['onEventDispatchContentTypeEvent', 10], - ], - ]; - } - - public function onCreateEntity(CreateEntityEvent $event): void - { - // set dummy version - $version = new stdClass(); - $version->file = null; - $event->setEntity($version); - } - - public function onFormPrepareResolve(FormPrepareEvent $event): void - { - $event->setType($this->getOption($event->getRequest(), 'type')); - $event->setFormOptions([ - 'method' => 'POST', - 'content_config' => $event->getRequest()->attributes->get('_content_config'), - ]); - } - - public function onApply(ApplyEvent $event): void - { - /** @var UploadedFile $zipFile */ - $zipFile = $event->getForm()->get('file')->getData(); - - $this->dataImporter->import(ZipContent::read($zipFile->getPath(), $zipFile->getBasename()), ['version_origin' => ContentVersionInterface::ORIGIN_IMPORT]); - - // $this->serializer->load('zip', [ - // 'zip_filename' => $zipFile->getPathname(), - // 'version_origin' => ContentVersionInterface::ORIGIN_IMPORT, - // 'persist_and_flush' => true, - // ]); - - $event->setApplied(true); - } - - /** - * @noinspection PhpRouteMissingInspection - */ - public function onSuccess(SuccessEvent $event): void - { - $contentConfig = $event->getRequest()->attributes->get('_content_config'); - - $this->flashNotifier->addTrans('success', "admin_{$contentConfig['_id']}.import.success_flash", [], 'sfs_cms_contents'); - - $url = $this->router->generate("sfs_cms_admin_content_{$contentConfig['_id']}_list"); - - $event->setResponse(new RedirectResponse($url)); - } - - public function onFailure(FailureEvent $event): void - { - $contentConfig = $event->getRequest()->attributes->get('_content_config'); - - if ($event->getException() instanceof UniqueConstraintViolationException) { - $this->flashNotifier->addTrans('error', "admin_{$contentConfig['_id']}.import.duplicated_flash", ['%exception%' => ''], 'sfs_cms_contents'); - } else { - $exception = $event->getException()->getMessage(); - if ('1' === $event->getRequest()->server->get('APP_DEBUG')) { - $exception .= '

'.get_class($event->getException()); - $exception .= '

'.nl2br($event->getException()->getTraceAsString()); - } - $this->flashNotifier->addTrans('error', "admin_{$contentConfig['_id']}.import.failed_flash", ['%exception%' => $exception], 'sfs_cms_contents'); - } - - $url = $this->router->generate("sfs_cms_admin_content_{$contentConfig['_id']}_list"); - - $event->setResponse(new RedirectResponse($url)); - } - - /** - * @noinspection PhpRouteMissingInspection - */ - public function onException(ExceptionEvent $event): void - { - $contentConfig = $event->getRequest()->attributes->get('_content_config'); - - if ($event->getException() instanceof MissingFormTypeException) { - $this->flashNotifier->addTrans('error', "admin_{$contentConfig['_id']}.version_import.module_not_configured_flash", ['%module%' => $event->getException()->getDiscriminator()], 'sfs_cms_contents'); - - $url = $this->router->generate("sfs_cms_admin_content_{$event->getRequest()->attributes->get('_content_config')['_id']}_details", ['content' => $event->getRequest()->attributes->get('content')]); - $event->setResponse(new RedirectResponse($url)); - } - } -} diff --git a/src/Admin/ActionListener/ContentVersion/ExportListener.php b/src/Admin/ActionListener/ContentVersion/ExportListener.php deleted file mode 100644 index 815afadf..00000000 --- a/src/Admin/ActionListener/ContentVersion/ExportListener.php +++ /dev/null @@ -1,127 +0,0 @@ - [ - ['onInitializeGetConfig', 20], - ['onEventDispatchContentTypeEvent', 10], - ['onEventLoadContentEntity', 9], - ['onInitializeUpdateHelperConfig', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_LOAD_ENTITY => [ - ['onEventDispatchContentTypeEvent', 10], - ['onLoadEntity', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_NOT_FOUND => [ - ['onEventDispatchContentTypeEvent', 10], - ['onNotFoundAddFlash', 5], - ['onNotFoundRedirectToList', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_FOUND => [ - ['onEventDispatchContentTypeEvent', 10], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_APPLY => [ - ['onEventDispatchContentTypeEvent', 10], - ['onApply', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_SUCCESS => [ - ['onEventDispatchContentTypeEvent', 10], - ['onSuccess', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_FAILURE => [ - ['onEventDispatchContentTypeEvent', 10], - ['onFailureOrException', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_EXPORT_EXCEPTION => [ - ['onEventDispatchContentTypeEvent', 10], - ['onFailureOrException', 0], - ], - ]; - } - - public function onApply(ApplyEvent $event): void - { - $event->setApplied(true); - - $contentConfig = $event->getRequest()->attributes->get('_content_config'); - - /** @var ContentVersionInterface $version */ - $version = $event->getEntity(); - /** @var ContentInterface $content */ - $content = $event->getRequest()->attributes->get('content'); - - // $exportName = sprintf('%s-%s-v%s-%s.zip', Slugger::lowerSlug($content->getName()), $contentConfig['_id'], $version->getVersionNumber(), date('Y-m-d-H-i-s')); - // $this->serializer->dump(['contents' => [$content]], 'zip', [ - // 'zip_filename' => $exportName, - // 'encoder' => 'yaml', - // 'dump_version' => ContentEntityNormalizer::DUMP_VERSION_ID, - // 'version_id' => $version->getId(), - // ]); - // - // $event->setResponse(ZipContent::response($exportName)); - - $path = tempnam(sys_get_temp_dir(), 'content_'); - unlink($path); - $this->dataExporter->exportContent($content, $version, $contentConfig, $path); - $exportName = sprintf('%s/%s-%s-v%s-%s.zip', sys_get_temp_dir(), Slugger::lowerSlug($content->getName()), $contentConfig['_id'], $version->getVersionNumber(), date('Y-m-d-H-i-s')); - - $event->setEntity(ZipContent::dumpResponse($path, $exportName)); - } - - public function onSuccess(SuccessEvent $event): void - { - if ($event->getEntity() instanceof Response) { - $event->setResponse($event->getEntity()); - } - } - - public function onFailureOrException(ExceptionEvent|FailureEvent $event): void - { - $contentConfig = $event->getRequest()->attributes->get('_content_config'); - - $this->flashNotifier->addTrans('error', "admin_{$contentConfig['_id']}.version_export.failed_flash", ['%exception%' => $event->getException()->getMessage()], 'sfs_cms_contents'); - - $content = $event->getRequest()->attributes->get('content'); - - $event->setResponse($this->redirectBack($contentConfig['_id'], $content, $event->getRequest())); - } -} diff --git a/src/Admin/ActionListener/ContentVersion/ImportListener.php b/src/Admin/ActionListener/ContentVersion/ImportListener.php deleted file mode 100644 index 181e0c0b..00000000 --- a/src/Admin/ActionListener/ContentVersion/ImportListener.php +++ /dev/null @@ -1,193 +0,0 @@ - [ - ['onInitializeGetConfig', 20], - ['onEventDispatchContentTypeEvent', 10], - ['onEventLoadContentEntity', 9], - ['onInitializeUpdateHelperConfig', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_ENTITY => [ - ['onEventDispatchContentTypeEvent', 10], - ['onCreateEntity', 1], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_PREPARE => [ - ['onEventDispatchContentTypeEvent', 10], - ['onFormPrepareResolve', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_INIT => [ - ['onEventDispatchContentTypeEvent', 10], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_VALID => [ - ['onEventDispatchContentTypeEvent', 10], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_APPLY => [ - ['onEventDispatchContentTypeEvent', 10], - ['onApply', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_SUCCESS => [ - ['onEventDispatchContentTypeEvent', 10], - ['onSuccess', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FAILURE => [ - ['onEventDispatchContentTypeEvent', 10], - ['onFailure', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_FORM_INVALID => [ - ['onEventDispatchContentTypeEvent', 10], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_VIEW => [ - ['onEventDispatchContentTypeEvent', 10], - ['onView', 0], - ], - SfsCmsEvents::ADMIN_CONTENT_VERSIONS_IMPORT_EXCEPTION => [ - ['onEventDispatchContentTypeEvent', 10], - ], - ]; - } - - public function onCreateEntity(CreateEntityEvent $event): void - { - // set dummy version - $version = new stdClass(); - $version->file = null; - $event->setEntity($version); - } - - public function onFormPrepareResolve(FormPrepareEvent $event): void - { - $event->setType($this->getOption($event->getRequest(), 'type')); - $event->setFormOptions([ - 'method' => 'POST', - 'content_config' => $event->getRequest()->attributes->get('_content_config'), - ]); - } - - public function onApply(ApplyEvent $event): void - { - // prevent default apply - $event->setApplied(true); - - $request = $event->getRequest(); - $contentConfig = $request->attributes->get('_content_config'); - $entity = $request->attributes->get('content'); - $form = $event->getForm(); - - /** @var UploadedFile $zipFile */ - $zipFile = $form->get('file')->getData(); - - // $this->serializer->load('zip', [ - // 'zip_filename' => $zipFile->getPathname(), - // 'content_to_load_version' => $entity, - // 'version_origin' => ContentVersionInterface::ORIGIN_IMPORT, - // 'version_origin_description' => $zipFile->getClientOriginalName(), - // 'version_keep' => true, - // 'persist_and_flush' => true, - // ]); - - $data = ZipContent::read($zipFile->getPath(), $zipFile->getBasename()); - - foreach ($data['contents'] as $content) { - $contentType = key($content); - $contentData = current($content); - $versionData = $contentData['versions'][0]; - - if ($contentType !== $contentConfig['_id']) { - $form->addError(new FormError(sprintf('Incompatible types, you are trying to import a "%s" version to a "%s" content.', $contentType, $contentConfig['_id']))); - break; - } - - $version = $this->dataImporter->importVersion($contentType, $entity, $versionData, $data, ['version_origin' => ContentVersionInterface::ORIGIN_IMPORT]); - $version->setOriginDescription($zipFile->getClientOriginalName()); - $version->setKeep(true); - $this->contentManager->saveEntity($entity); - } - } - - /** - * @noinspection PhpRouteMissingInspection - */ - public function onSuccess(SuccessEvent $event): void - { - $request = $event->getRequest(); - $contentConfig = $request->attributes->get('_content_config'); - $content = $request->attributes->get('content'); - - $this->flashNotifier->addTrans('success', "admin_{$contentConfig['_id']}.version_import.success_flash", [], 'sfs_cms_contents'); - - if ($this->getOption($request, 'success_redirect_to')) { - $url = $this->router->generate($this->getOption($request, 'success_redirect_to'), ['content' => $content]); - } else { - $url = $this->router->generate("sfs_cms_admin_content_{$contentConfig['_id']}_versions", ['content' => $content]); - } - - $event->setResponse(new RedirectResponse($url)); - } - - public function onFailure(FailureEvent $event): void - { - $form = $event->getForm(); - $exception = $event->getException(); - - $form->addError(new FormError(sprintf('Han error has been produced during importing: %s', $exception->getMessage()))); - } - - /** - * @noinspection PhpRouteMissingInspection - */ - public function onException(ExceptionEvent $event): void - { - $contentConfig = $event->getRequest()->attributes->get('_content_config'); - - if ($event->getException() instanceof MissingFormTypeException) { - $this->flashNotifier->addTrans('error', "admin_{$contentConfig['_id']}.version_import.module_not_configured_flash", ['%module%' => $event->getException()->getDiscriminator()], 'sfs_cms_contents'); - - $url = $this->router->generate("sfs_cms_admin_content_{$event->getRequest()->attributes->get('_content_config')['_id']}_details", ['content' => $event->getRequest()->attributes->get('content')]); - $event->setResponse(new RedirectResponse($url)); - } - } -} diff --git a/src/Command/DumpFixturesCommand.php b/src/Command/DumpFixturesCommand.php deleted file mode 100644 index 5f0456f5..00000000 --- a/src/Command/DumpFixturesCommand.php +++ /dev/null @@ -1,104 +0,0 @@ -dataExporter = $dataExporter; - $this->em = $em; - $this->cmsConfig = $cmsConfig; - } - - protected function configure(): void - { - $this->setName('sfs:cms:dump-fixtures'); - $this->addArgument('elements', InputArgument::OPTIONAL); - } - - protected function execute(InputInterface $input, OutputInterface $output): int - { - $output->writeln('Removed fixtures/media files'); - $mediaPath = '/srv/cms/fixtures/media'; - array_map('unlink', glob("$mediaPath/*.*")); - if (is_dir($mediaPath)) { - rmdir($mediaPath); - } - - $elements = $input->getArgument('elements'); - - $elementTypes = ['contents', 'routes', 'menus', 'blocks']; - if ($elements && !in_array($elements, $elementTypes)) { - $output->writeln(sprintf('Invalid "%s" element type, use: %s', $elements, implode(', ', $elementTypes))); - - return Command::INVALID; - } - - if (!$elements || 'contents' == $elements) { - $this->dumpContents($output); - } - if (!$elements || 'routes' == $elements) { - $this->dumpRoutes($output); - } - if (!$elements || 'menus' == $elements) { - $this->dumpMenus($output); - } - if (!$elements || 'blocks' == $elements) { - $this->dumpBlocks($output); - } - - return Command::SUCCESS; - } - - protected function dumpContents(OutputInterface $output) - { - foreach ($this->cmsConfig->getContents() as $contentConfig) { - /** @var ContentInterface $content */ - foreach ($this->em->getRepository($contentConfig['entity_class'])->findAll() as $content) { - $this->dataExporter->exportContent($content, $content->getVersions()->first() ?: null, $contentConfig, '/srv/cms/fixtures', ['output' => $output]); - } - } - } - - protected function dumpRoutes(OutputInterface $output) - { - /** @var RouteInterface $route */ - foreach ($this->em->getRepository(RouteInterface::class)->findAll() as $route) { - $this->dataExporter->exportRoute($route, '/srv/cms/fixtures', ['output' => $output]); - } - } - - protected function dumpMenus(OutputInterface $output) - { - /** @var MenuInterface $menu */ - foreach ($this->em->getRepository(MenuInterface::class)->findAll() as $menu) { - $this->dataExporter->exportMenu($menu, '/srv/cms/fixtures', ['output' => $output]); - } - } - - protected function dumpBlocks(OutputInterface $output) - { - /** @var BlockInterface $block */ - foreach ($this->em->getRepository(BlockInterface::class)->findAll() as $block) { - $this->dataExporter->exportBlock($block, '/srv/cms/fixtures', ['output' => $output]); - } - } -} diff --git a/src/Config/Model/Content.php b/src/Config/Model/Content.php index a7f2b8fb..d85f3dbf 100644 --- a/src/Config/Model/Content.php +++ b/src/Config/Model/Content.php @@ -6,13 +6,11 @@ use Softspring\CmsBundle\Form\Admin\Content\ContentDeleteForm; use Softspring\CmsBundle\Form\Admin\Content\ContentDiffForm; use Softspring\CmsBundle\Form\Admin\Content\ContentDuplicateForm; -use Softspring\CmsBundle\Form\Admin\Content\ContentImportForm; use Softspring\CmsBundle\Form\Admin\Content\ContentListFilterForm; use Softspring\CmsBundle\Form\Admin\Content\ContentRoutesForm; use Softspring\CmsBundle\Form\Admin\Content\ContentUpdateForm; use Softspring\CmsBundle\Form\Admin\ContentVersion\VersionCreateForm; use Softspring\CmsBundle\Form\Admin\ContentVersion\VersionDeleteForm; -use Softspring\CmsBundle\Form\Admin\ContentVersion\VersionImportForm; use Softspring\CmsBundle\Form\Admin\ContentVersion\VersionListFilterForm; use Softspring\CmsBundle\Form\Admin\ContentVersion\VersionSeoForm; use Softspring\CmsBundle\Form\Admin\ContentVersion\VersionUpdateForm; @@ -153,14 +151,6 @@ public function getConfigTreeBuilder(): TreeBuilder 'create_view' => 'create.view', 'create_type' => 'create.type', 'create_success_redirect_to' => 'create.success_redirect_to', - 'import_is_granted' => 'import.is_granted', - 'import_view' => 'import.view', - 'import_type' => 'import.type', - 'import_success_redirect_to' => 'import.success_redirect_to', - 'version_import_is_granted' => 'import.version_is_granted', - 'version_import_view' => 'import.version_view', - 'version_import_type' => 'import.version_type', - 'version_import_success_redirect_to' => 'import.version_success_redirect_to', 'read_is_granted' => 'read.is_granted', 'read_view' => 'read.view', 'preview_is_granted' => 'preview.is_granted', @@ -169,7 +159,6 @@ public function getConfigTreeBuilder(): TreeBuilder 'versions_view' => 'version_list.view', 'cleanup_versions_is_granted' => 'version_cleanup.is_granted', 'keep_version_is_granted' => 'version_lock.is_granted', - 'export_version_is_granted' => 'export_version.is_granted', 'update_is_granted' => 'update.is_granted', 'update_view' => 'update.view', 'update_type' => 'update.type', @@ -212,14 +201,6 @@ public function getConfigTreeBuilder(): TreeBuilder ->scalarNode('create_view')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('create_type')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('create_success_redirect_to')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('import_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('import_view')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('import_type')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('import_success_redirect_to')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('version_import_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('version_import_view')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('version_import_type')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('version_import_success_redirect_to')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('read_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('read_view')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('preview_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() @@ -228,7 +209,6 @@ public function getConfigTreeBuilder(): TreeBuilder ->scalarNode('versions_view')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('cleanup_versions_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('keep_version_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() - ->scalarNode('export_version_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('update_is_granted')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('update_view')->setDeprecated('softspring/cms-bundle', '5.2')->end() ->scalarNode('update_type')->setDeprecated('softspring/cms-bundle', '5.2')->end() @@ -267,27 +247,6 @@ public function getConfigTreeBuilder(): TreeBuilder ->scalarNode('success_redirect_to')->defaultValue('')->end() ->end() ->end() - - ->arrayNode('import') - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('is_granted')->defaultValue('PERMISSION_SFS_CMS_ADMIN_CONTENT_IMPORT')->end() - ->scalarNode('view')->defaultValue('@SfsCms/admin/content/import.html.twig')->end() - ->scalarNode('type')->defaultValue(ContentImportForm::class)->end() - ->scalarNode('success_redirect_to')->defaultValue('')->end() - ->end() - ->end() - - ->arrayNode('version_import') - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('is_granted')->defaultValue('PERMISSION_SFS_CMS_ADMIN_CONTENT_VERSION_IMPORT')->end() - ->scalarNode('view')->defaultValue('@SfsCms/admin/content/version_import.html.twig')->end() - ->scalarNode('type')->defaultValue(VersionImportForm::class)->end() - ->scalarNode('success_redirect_to')->defaultValue('')->end() - ->end() - ->end() - ->arrayNode('read') ->addDefaultsIfNotSet() ->children() @@ -344,13 +303,6 @@ public function getConfigTreeBuilder(): TreeBuilder ->scalarNode('is_granted')->defaultValue('PERMISSION_SFS_CMS_ADMIN_CONTENT_VERSION_CLEAR_COMPILED')->end() ->end() ->end() - ->arrayNode('export_version') - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('is_granted')->defaultValue('PERMISSION_SFS_CMS_ADMIN_CONTENT_VERSION_EXPORT')->end() - ->end() - ->end() - ->arrayNode('update') ->addDefaultsIfNotSet() ->children() diff --git a/src/Data/AbstractDataImportExport.php b/src/Data/AbstractDataImportExport.php deleted file mode 100644 index 7d02eb72..00000000 --- a/src/Data/AbstractDataImportExport.php +++ /dev/null @@ -1,40 +0,0 @@ -entityTransformers = $entityTransformers; - } - - /** - * @throws DataTransformerNotFoundException - */ - protected function getDataTransformer(string $type, $data = null): EntityTransformerInterface - { - /** @var EntityTransformerInterface $transformer */ - foreach ($this->entityTransformers as $transformer) { - if ($transformer->supports($type, $data)) { - return $transformer; - } - } - - throw new DataTransformerNotFoundException($type); - } -} diff --git a/src/Data/DataExporter.php b/src/Data/DataExporter.php deleted file mode 100644 index bf2d9e4e..00000000 --- a/src/Data/DataExporter.php +++ /dev/null @@ -1,135 +0,0 @@ -referenceRepository = new ReferencesRepository(); - } - - public function export(array $contents, array $options = []): void - { - } - - public function exportRoute(RouteInterface $route, string $path, array $options = []): string - { - if (!is_dir("$path/routes")) { - mkdir("$path/routes", 0755, true); - } - - $exportFile = YamlContent::save($this->getDataTransformer('routes', $route)->export($route), "$path/routes/{$route->getId()}.yaml"); - - ($options['output'] ?? false) && $options['output']->writeln(sprintf('Exported "%s" route to %s', $route->getId(), $exportFile)); - - return $exportFile; - } - - public function exportMenu(MenuInterface $menu, string $path, array $options = []): string - { - if (!is_dir("$path/menus")) { - mkdir("$path/menus", 0755, true); - } - - $exportFile = YamlContent::save($this->getDataTransformer('menus', $menu)->export($menu), "$path/menus/".Slugger::lowerSlug($menu->getName()).'.yaml'); - - ($options['output'] ?? false) && $options['output']->writeln(sprintf('Exported "%s" menu to %s', $menu->getId(), $exportFile)); - - return $exportFile; - } - - public function exportBlock(BlockInterface $block, string $path, array $options = []): string - { - if (!is_dir("$path/blocks")) { - mkdir("$path/blocks", 0755, true); - } - - $exportFile = YamlContent::save($this->getDataTransformer('blocks', $block)->export($block), "$path/blocks/".Slugger::lowerSlug($block->getName()).'.yaml'); - - ($options['output'] ?? false) && $options['output']->writeln(sprintf('Exported "%s" block to %s', $block->getId(), $exportFile)); - - return $exportFile; - } - - public function exportContent(ContentInterface $content, ?ContentVersionInterface $contentVersion, array $contentTypeConfig, string $path, array $options = []): string - { - $contentType = $contentTypeConfig['_id']; - - if (!is_dir("$path/contents")) { - mkdir("$path/contents", 0755, true); - } - $file = "$path/contents/".Slugger::lowerSlug($content->getName()).'.yaml'; - $files = []; - /** @var ContentEntityTransformerInterface $transformer */ - $transformer = $this->getDataTransformer($contentType, $content); - $filePath = YamlContent::save($transformer->export($content, $files, $contentVersion, $contentType), $file); - - foreach ($content->getRoutes() as $route) { - $parentRoute = $route->getParent(); - while ($parentRoute) { - self::exportRoute($parentRoute, $path); - $parentRoute = $parentRoute->getParent(); - } - self::exportRoute($route, $path); - } - - foreach ($files as $fileName => $fileData) { - switch ($fileData['@type']) { - case 'json': - file_put_contents("$path/$fileName", json_encode($fileData['json'], JSON_PRETTY_PRINT)); - break; - - case 'file': - switch ($fileData['@location']) { - case 'gcs': - $storageClient = new StorageClient(); - if (!is_dir(dirname("$path/$fileName"))) { - mkdir(dirname("$path/$fileName"), 0755, true); - } - $storageClient->bucket($fileData['bucket'])->object($fileData['object'])->downloadToFile("$path/$fileName"); - break; - - case 'sfs-media-filesystem': - if (!is_dir(dirname("$path/$fileName"))) { - mkdir(dirname("$path/$fileName"), 0755, true); - } - copy($fileData['path'].'/'.$fileData['object'], "$path/$fileName"); - break; - - default: - throw new Exception('Not yet implemented'); - } - break; - - default: - throw new Exception('Not yet implemented'); - } - } - - ($options['output'] ?? false) && $options['output']->writeln(sprintf('Exported "%s" %s content to %s', $content->getName(), $contentType, $filePath)); - - return $filePath; - } -} diff --git a/src/Data/DataImporter.php b/src/Data/DataImporter.php deleted file mode 100644 index 39944b59..00000000 --- a/src/Data/DataImporter.php +++ /dev/null @@ -1,127 +0,0 @@ -em = $em; - $this->mediaManager = $mediaManager; - $this->cmsConfig = $cmsConfig; - $this->siteManager = $siteManager; - $this->referenceRepository = new ReferencesRepository(); - $this->cmsLogger = $cmsLogger; - } - - /** - * @throws DataTransformerNotFoundException - */ - public function import(array $contents, array $options = []): void - { - $this->cmsConfig->clearSites(); - $this->em->clear(); - // preload sites - foreach ($this->cmsConfig->getSites() as $site) { - $this->cmsLogger && $this->cmsLogger->info(sprintf('Preload site "%s"', "$site")); - $this->referenceRepository->addReference("site___{$site}", $site); - } - - // do preloading - foreach ($contents as $type => $elements) { - foreach ($elements as $data) { - $this->cmsLogger && $this->cmsLogger->debug(sprintf('Preload "%s"', "$type")); - $this->getDataTransformer($type, $data)->preload($data, $this->referenceRepository); - } - } - - // import medias before to prevent errors - foreach ($contents['media'] ?? [] as $data) { - $this->cmsLogger && $this->cmsLogger->info(sprintf('Import media %s (%u/%u)', $data['media']['name'], isset($i) ? ++$i : $i = 1, count($contents['media']))); - $entity = $this->getDataTransformer('media', $data)->import($data, $this->referenceRepository, $options); - $this->em->persist($entity); - $this->em->flush(); - } - unset($contents['media']); - - // import parent routes before to allow import children - foreach ($contents['routes'] ?? [] as $routeData) { - if (RouteInterface::TYPE_PARENT_ROUTE === $routeData['route']['type']) { - $this->cmsLogger && $this->cmsLogger->info(sprintf('Import parent route "%s"', $routeData['route']['id'])); - $parentRoute = $this->getDataTransformer('routes', $routeData)->import($routeData, $this->referenceRepository, $options); - $this->em->persist($parentRoute); - } - } - $this->em->flush(); - - // import rest of contents - foreach (['routes', 'blocks', 'menus', 'contents'] as $type) { - $elements = $contents[$type] ?? []; - foreach ($elements as $data) { - if ('routes' !== $type || RouteInterface::TYPE_PARENT_ROUTE !== $data['route']['type']) { - $dataName = $data[$type]['name'] ?? $data[$type]['id'] ?? current($data)['name'] ?? ''; - - $this->cmsLogger && $this->cmsLogger->info(sprintf('Import %s "%s"', $type, $dataName)); - $entity = $this->getDataTransformer($type, $data)->import($data, $this->referenceRepository, $options); - $this->em->persist($entity); - } - } - } - $this->em->flush(); - } - - public function importVersion(string $type, ContentInterface $content, array $versionData, array $zipData, array $options = []): ?ContentVersionInterface - { - // preload sites - foreach ($this->cmsConfig->getSites() as $site) { - $this->referenceRepository->addReference("site___{$site}", $site); - } - - $transformer = $this->getDataTransformer($type); - - if (!$transformer instanceof ContentEntityTransformerInterface) { - throw new Exception('Invalid entity transformer, check configuration'); - } - - foreach ($zipData['media'] as $id => $mediaData) { - $media = $this->mediaManager->getRepository()->findOneById($id); - - if ($media) { - $this->referenceRepository->addReference("media___{$id}", $media); - } else { - $this->getDataTransformer('media', $mediaData)->preload($mediaData, $this->referenceRepository); - $entity = $this->getDataTransformer('media', $mediaData)->import($mediaData, $this->referenceRepository, $options); - $this->em->persist($entity); - } - } - - return $transformer->importVersion($content, $versionData['layout'], $versionData['data'] ?? [], $versionData['seo'] ?? [], $this->referenceRepository, $options); - } -} diff --git a/src/Data/DataTransformer.php b/src/Data/DataTransformer.php deleted file mode 100644 index 8e0f23c2..00000000 --- a/src/Data/DataTransformer.php +++ /dev/null @@ -1,46 +0,0 @@ -fieldTransformers = $fieldTransformers; - } - - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options): mixed - { - foreach ($this->fieldTransformers as $fieldTransformer) { - if ($fieldTransformer->supportsImport('', $data)) { - return $fieldTransformer->import($data, $referencesRepository, $options); - } - } - - return $data; - } - - public function export(mixed $data, &$files = []): mixed - { - foreach ($this->fieldTransformers as $fieldTransformer) { - if ($fieldTransformer->supportsExport('', $data)) { - return $fieldTransformer->export($data, $files); - } - } - - return $data; - } -} diff --git a/src/Data/EntityTransformer/BlockEntityTransformer.php b/src/Data/EntityTransformer/BlockEntityTransformer.php deleted file mode 100644 index 714c2568..00000000 --- a/src/Data/EntityTransformer/BlockEntityTransformer.php +++ /dev/null @@ -1,81 +0,0 @@ -blockManager = $blockManager; - $this->dataTransformer = $dataTransformer; - } - - public static function getPriority(): int - { - return 0; - } - - public function supports(string $type, $data = null): bool - { - return 'blocks' === $type; - } - - public function export(object $element, &$files = []): array - { - if (!$element instanceof BlockInterface) { - throw new InvalidElementException(sprintf('%s dumper requires that $element to be an instance of %s, %s given.', get_called_class(), BlockInterface::class, get_class($element))); - } - - $block = $element; - - return [ - 'block' => [ - 'type' => $block->getType(), - 'name' => $block->getName(), - 'publish_start_date' => $block->getPublishStartDate() instanceof DateTime ? $block->getPublishStartDate()->format('Y-m-d H:i:s') : null, - 'publish_end_date' => $block->getPublishEndDate() instanceof DateTime ? $block->getPublishEndDate()->format('Y-m-d H:i:s') : null, - 'data' => $this->dataTransformer->export($block->getData(), $files), - ], - ]; - } - - public function preload(array $data, ReferencesRepository $referencesRepository): void - { - $blockId = Slugger::lowerSlug($data['block']['name']); - $referencesRepository->addReference("block___{$blockId}", $this->blockManager->createEntity($data['block']['type'])); - } - - public function import(array $data, ReferencesRepository $referencesRepository, array $options = []): BlockInterface - { - try { - $blockId = Slugger::lowerSlug($data['block']['name']); - /** @var BlockInterface $block */ - $block = $referencesRepository->getReference("block___{$blockId}", true); - } catch (ReferenceNotFoundException $e) { - throw new RunPreloadBeforeImportException('You must call preload() method before importing', 0, $e); - } - - $block->setName($data['block']['name']); - $block->setData($data['block']['data']); - $block->setPublishStartDate($data['block']['publish_start_date'] ? new DateTime($data['block']['publish_start_date']) : null); - $block->setPublishEndDate($data['block']['publish_end_date'] ? new DateTime($data['block']['publish_end_date']) : null); - - return $block; - } -} diff --git a/src/Data/EntityTransformer/ContentEntityTransformer.php b/src/Data/EntityTransformer/ContentEntityTransformer.php deleted file mode 100644 index 1dd14b04..00000000 --- a/src/Data/EntityTransformer/ContentEntityTransformer.php +++ /dev/null @@ -1,163 +0,0 @@ -contentManager = $contentManager; - $this->routeManager = $routeManager; - $this->mediaManager = $mediaManager; - $this->siteManager = $siteManager; - $this->dataTransformer = $dataTransformer; - } - - public static function getPriority(): int - { - return 0; - } - - public function supports(string $type, $data = null): bool - { - if ('contents' === $type) { - return true; - } - - return 'page' === $type; - } - - public function export(object $element, &$files = [], ?object $contentVersion = null, ?string $contentType = null): array - { - if (!$element instanceof ContentInterface) { - throw new InvalidElementException(sprintf('%s dumper requires that $element to be an instance of %s, %s given.', get_called_class(), ContentInterface::class, get_class($element))); - } - if ($contentVersion && !$contentVersion instanceof ContentVersionInterface) { - throw new InvalidElementException(sprintf('%s dumper requires that $contentVersion to be an instance of %s, %s given.', get_called_class(), ContentVersionInterface::class, get_class($contentVersion))); - } - if (!$contentType) { - throw new InvalidElementException(sprintf('%s dumper requires $contentType', get_called_class())); - } - - $content = $element; - - $files = []; - - $versions = []; - - if ($contentVersion instanceof ContentVersionInterface) { - $versions[] = [ - 'seo' => $this->dataTransformer->export($contentVersion->getSeo()), - 'layout' => $contentVersion->getLayout(), - 'data' => $this->dataTransformer->export($contentVersion->getData(), $files), - 'version_number' => $contentVersion->getVersionNumber(), - 'origin' => $contentVersion->getOrigin(), - 'origin_description' => $contentVersion->getOriginDescription(), - 'note' => $contentVersion->getNote(), - 'created_at' => $contentVersion->getCreatedAt() instanceof DateTime ? $contentVersion->getCreatedAt()->format('Y-m-d H:i:s') : null, - 'meta' => $contentVersion->getMeta(), - ]; - } - - return [ - $contentType => [ - 'name' => $content->getName(), - 'default_locale' => $content->getDefaultLocale(), - 'locales' => $content->getLocales(), - 'sites' => $content->getSites()->map(fn (SiteInterface $site): ?string => $site->getId())->toArray(), - 'extra' => $content->getExtraData(), - 'indexing' => $content->getIndexing(), - 'versions' => $versions, - ], - ]; - } - - public function preload(array $data, ReferencesRepository $referencesRepository): void - { - $contentType = key($data); - $contentData = $data[$contentType]; - $id = Slugger::lowerSlug($contentData['name']); - - $referencesRepository->addReference("content___{$id}", $this->contentManager->createEntity($contentType)); - } - - public function import(array $data, ReferencesRepository $referencesRepository, array $options = []): ContentInterface - { - $contentType = key($data); - $contentData = $data[$contentType]; - $id = Slugger::lowerSlug($contentData['name']); - - try { - /** @var ContentInterface $content */ - $content = $referencesRepository->getReference("content___{$id}", true); - } catch (ReferenceNotFoundException $e) { - throw new RunPreloadBeforeImportException('You must call preload() method before importing', 0, $e); - } - - // cleanup versions - $content->removeVersion($content->getVersions()->first()); - - $content->setName($contentData['name']); - - // @deprecated: FIX OLD FIXTURES - $contentData['sites'] = isset($contentData['site']) ? [$contentData['site']] : $contentData['sites']; - - foreach ($contentData['sites'] as $site) { - $content->addSite($referencesRepository->getReference("site___{$site}", true)); - } - - $content->setDefaultLocale($contentData['default_locale'] ?? null); - $content->setLocales($contentData['locales'] ?? []); - - $content->setExtraData($contentData['extra']); - - $content->setIndexing($contentData['indexing'] ?? []); - - foreach ($contentData['versions'] as $version) { - if ($version['layout'] && $version['data']) { - $version = $this->importVersion($content, $version['layout'], $version['data'], $version['seo'], $referencesRepository, $options); - if ($options['auto_publish_version'] ?? false) { - $content->setPublishedVersion($version); - } - } - } - - return $content; - } - - public function importVersion(ContentInterface $content, string $layout, array $data, ?array $seo, ReferencesRepository $referencesRepository, array $options = []): ContentVersionInterface - { - $version = $this->contentManager->createVersion($content, null, $options['version_origin'] ?? ContentVersionInterface::ORIGIN_UNKNOWN); - $version->setLayout($layout); - $version->setData($this->dataTransformer->import($data, $referencesRepository, $options)); - $version->setSeo($this->dataTransformer->import($seo, $referencesRepository, $options)); - - // TODO set version number and other metadata fields - - return $version; - } -} diff --git a/src/Data/EntityTransformer/ContentEntityTransformerInterface.php b/src/Data/EntityTransformer/ContentEntityTransformerInterface.php deleted file mode 100644 index 266b0f0a..00000000 --- a/src/Data/EntityTransformer/ContentEntityTransformerInterface.php +++ /dev/null @@ -1,23 +0,0 @@ -mediaManager = $mediaManager; - $this->mediaVersionManager = $mediaVersionManager; - } - - public static function getPriority(): int - { - return 0; - } - - public function supports(string $type, $data = null): bool - { - return 'media' === $type; - } - - public function export(object $element, &$files = []): array - { - // TODO: Implement export() method. - return []; - } - - public function preload(array $data, ReferencesRepository $referencesRepository): void - { - $media = $this->mediaManager->createEntity(); - $media->setDescription($data['media']['id']); - $referencesRepository->addReference("media___{$data['media']['id']}", $media); - } - - public function import(array $data, ReferencesRepository $referencesRepository, array $options = []): MediaInterface - { - $mediaData = $data['media']; - - try { - /** @var MediaInterface $media */ - $media = $referencesRepository->getReference("media___{$mediaData['id']}", true); - } catch (ReferenceNotFoundException $e) { - throw new RunPreloadBeforeImportException('You must call preload() method before importing', 0, $e); - } - - $media->setMediaType($data['media']['media_type']); - $media->setType($data['media']['type']); - $media->setName($data['media']['name']); - $media->setDescription($data['media']['description']); - - foreach ($data['media']['versionFiles'] as $versionKey => $versionFileName) { - $file = $data['files'][$versionFileName]; - - $version = $this->mediaVersionManager->createEntity(); - $version->setVersion($versionKey); - $version->setUpload(new UploadedFile($file['tmpPath'], $file['name']), true); - $media->addVersion($version); - } - - return $media; - } -} diff --git a/src/Data/EntityTransformer/MenuEntityTransformer.php b/src/Data/EntityTransformer/MenuEntityTransformer.php deleted file mode 100644 index df8725e1..00000000 --- a/src/Data/EntityTransformer/MenuEntityTransformer.php +++ /dev/null @@ -1,99 +0,0 @@ -menuManager = $menuManager; - $this->menuItemManager = $menuItemManager; - } - - public static function getPriority(): int - { - return 0; - } - - public function supports(string $type, $data = null): bool - { - return 'menus' === $type; - } - - public function export(object $element, &$files = []): array - { - if (!$element instanceof MenuInterface) { - throw new InvalidElementException(sprintf('%s dumper requires that $element to be an instance of %s, %s given.', get_called_class(), MenuInterface::class, get_class($element))); - } - $menu = $element; - - $dump = [ - 'menu' => [ - 'type' => $menu->getType(), - 'name' => $menu->getName(), - 'items' => [], - ], - ]; - - foreach ($menu->getItems() as $item) { - $dump['menu']['items'][] = [ - 'text' => $item->getText(), - 'symfony_route' => $item->getSymfonyRoute(), - ]; - } - - return $dump; - } - - public function preload(array $data, ReferencesRepository $referencesRepository): void - { - $menuId = Slugger::lowerSlug($data['menu']['name']); - $referencesRepository->addReference("menu___{$menuId}", $this->menuManager->createEntity($data['menu']['type'])); - } - - public function import(array $data, ReferencesRepository $referencesRepository, array $options = []): MenuInterface - { - $menuId = Slugger::lowerSlug($data['menu']['name']); - - try { - /** @var MenuInterface $menu */ - $menu = $referencesRepository->getReference("menu___{$menuId}", true); - } catch (ReferenceNotFoundException $e) { - throw new RunPreloadBeforeImportException('You must call preload() method before importing', 0, $e); - } - - $menu->setName($data['menu']['name']); - - foreach ($data['menu']['items'] as $item) { - $this->createMenuItem($menu, $item['text'], $item['symfony_route']); - } - - return $menu; - } - - public function createMenuItem(MenuInterface $menu, array $text, ?array $route = null): MenuItemInterface - { - $item = $this->menuItemManager->createEntity(); - $menu->addItem($item); - $item->setText($text); - $item->setSymfonyRoute($route); - - return $item; - } -} diff --git a/src/Data/EntityTransformer/PageEntityTransformer.php b/src/Data/EntityTransformer/PageEntityTransformer.php deleted file mode 100644 index 692abf78..00000000 --- a/src/Data/EntityTransformer/PageEntityTransformer.php +++ /dev/null @@ -1,10 +0,0 @@ -routeManager = $routeManager; - $this->routePathManager = $routePathManager; - $this->siteManager = $siteManager; - } - - public static function getPriority(): int - { - return 0; - } - - public function supports(string $type, $data = null): bool - { - return 'routes' === $type; - } - - public function export(object $element, &$files = []): array - { - if (!$element instanceof RouteInterface) { - throw new InvalidElementException(sprintf('%s dumper requires that $element to be an instance of %s, %s given.', get_called_class(), RouteInterface::class, get_class($element))); - } - $route = $element; - - $dump = [ - 'route' => [ - 'id' => $route->getId(), - 'sites' => $route->getSites()->map(fn (SiteInterface $site): ?string => $site->getId())->toArray(), - 'type' => $route->getType(), - 'parent' => $route->getParent()?->getId(), - 'symfony_route' => $route->getSymfonyRoute(), - 'content' => null, - 'redirect_type' => $route->getRedirectType(), - 'redirect_url' => $route->getRedirectUrl(), - 'paths' => [], - ], - ]; - - if ($route->getContent() instanceof ContentInterface) { - $dump['route']['content'] = Slugger::lowerSlug($route->getContent()->getName()); - } - - foreach ($route->getPaths() as $path) { - $dump['route']['paths'][] = [ - 'path' => $path->getPath(), - 'locale' => $path->getLocale(), - 'cache_ttl' => $path->getCacheTtl(), - ]; - } - - return $dump; - } - - public function preload(array $data, ReferencesRepository $referencesRepository): void - { - $referencesRepository->addReference("route___{$data['route']['id']}", $this->routeManager->createEntity()); - } - - public function import(array $data, ReferencesRepository $referencesRepository, array $options = []): RouteInterface - { - $routeData = $data['route']; - - try { - /** @var RouteInterface $route */ - $route = $referencesRepository->getReference("route___{$routeData['id']}", true); - } catch (ReferenceNotFoundException $e) { - throw new RunPreloadBeforeImportException('You must call preload() method before importing', 0, $e); - } - - $route->setId($routeData['id']); - - // @deprecated: FIX OLD FIXTURES - $routeData['sites'] = isset($routeData['site']) ? [$routeData['site']] : $routeData['sites']; - - foreach ($routeData['sites'] as $site) { - $route->addSite($referencesRepository->getReference("site___{$site}", true)); - } - - $route->setType(RouteInterface::TYPE_UNKNOWN); - - if ($routeData['parent'] ?? false) { - $route->setParent($referencesRepository->getReference("route___{$routeData['parent']}", true)); - } - - switch ($routeData['type']) { - case RouteInterface::TYPE_CONTENT: - $route->setContent($referencesRepository->getReference("content___{$routeData['content']}", true)); - break; - - case RouteInterface::TYPE_REDIRECT_TO_URL: - $route->setRedirectUrl($routeData['redirect_url']); - $route->setRedirectType($routeData['redirect_type']); - break; - - case RouteInterface::TYPE_REDIRECT_TO_ROUTE: - $route->setSymfonyRoute($routeData['symfony_route']); - break; - - case RouteInterface::TYPE_PARENT_ROUTE: - // nothing to do - break; - - default: - throw new Exception(sprintf('Route type %u not yet implemented', $routeData['type'])); - } - - // store valid type - $route->setType($routeData['type']); - - foreach ($route->getPaths() as $existingPath) { - $route->removePath($existingPath); - } - - foreach ($routeData['paths'] as $paths) { - $route->addPath($routePath = $this->routePathManager->createEntity()); - $routePath->setPath($paths['path']); - $routePath->setLocale($paths['locale'] ?? null); - $routePath->setCacheTtl($paths['cache_ttl'] ?? null); - } - - return $route; - } -} diff --git a/src/Data/Exception/DataTransformerNotFoundException.php b/src/Data/Exception/DataTransformerNotFoundException.php deleted file mode 100644 index 14324fe8..00000000 --- a/src/Data/Exception/DataTransformerNotFoundException.php +++ /dev/null @@ -1,17 +0,0 @@ -dataTransformer = $dataTransformer; - } - - public static function getPriority(): int - { - return 0; - } - - public function supportsExport(string $type, mixed $data): bool - { - return is_array($data); - } - - public function export(mixed $data, &$files = []): mixed - { - foreach ($data as $key => $value) { - $data[$key] = $this->dataTransformer->export($value, $files); - } - - return $data; - } - - public function supportsImport(string $type, mixed $data): bool - { - return is_array($data); - } - - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options = []): mixed - { - foreach ($data as $key => $value) { - $data[$key] = $this->dataTransformer->import($value, $referencesRepository, $options); - } - - return $data; - } -} diff --git a/src/Data/FieldTransformer/BlockFieldTransformer.php b/src/Data/FieldTransformer/BlockFieldTransformer.php deleted file mode 100644 index 9c8b7251..00000000 --- a/src/Data/FieldTransformer/BlockFieldTransformer.php +++ /dev/null @@ -1,40 +0,0 @@ - 'block___'.Slugger::lowerSlug($data->getName()), - ]; - } - - public function supportsImport(string $type, mixed $data): bool - { - return isset($data['_reference']) && str_starts_with($data['_reference'], 'block___'); - } - - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options = []): mixed - { - return $referencesRepository->getReference($data['_reference'], true); - } -} diff --git a/src/Data/FieldTransformer/DefaultTransformer.php b/src/Data/FieldTransformer/DefaultTransformer.php deleted file mode 100644 index 78c63954..00000000 --- a/src/Data/FieldTransformer/DefaultTransformer.php +++ /dev/null @@ -1,36 +0,0 @@ -em = $em; - } - - public static function getPriority(): int - { - return 10; - } - - public function supportsExport(string $type, mixed $data): bool - { - try { - if (!is_object($data)) { - return false; - } - - $this->em->getClassMetadata(get_class($data)); - - return true; - } catch (MappingException) { - return false; - } - } - - public function export(mixed $data, &$files = []): mixed - { - return [ - '_entity' => [ - 'class' => $this->em->getClassMetadata(get_class($data))->getName(), - 'id' => $this->em->getUnitOfWork()->getEntityIdentifier($data), - ], - ]; - } - - public function supportsImport(string $type, mixed $data): bool - { - return isset($data['_entity']) && isset($data['_entity']['class']) && isset($data['_entity']['id']); - } - - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options = []): mixed - { - return $this->em->getRepository($data['_entity']['class'])->findOneBy($data['_entity']['id']); - } -} diff --git a/src/Data/FieldTransformer/FieldTransformerInterface.php b/src/Data/FieldTransformer/FieldTransformerInterface.php deleted file mode 100644 index f3fe0b31..00000000 --- a/src/Data/FieldTransformer/FieldTransformerInterface.php +++ /dev/null @@ -1,21 +0,0 @@ -getVersion('_original'); - $mediaFileName = 'media/'.$data->getId().([ - 'image/jpeg' => '.jpeg', - 'image/png' => '.png', - 'image/gif' => '.gif', - 'image/webp' => '.webp', - 'image/svg+xml' => '.svg', - 'video/webm' => '.webm', - ][$originalVersion->getFileMimeType()] ?? ''); - $versionFiles['_original'] = $mediaFileName; - - $url = $originalVersion->getUrl(); - $protocol = explode('://', $url)[0]; - $urlWithoutProtocol = substr($url, strlen($protocol) + 3); - $urlParts = explode('/', $urlWithoutProtocol); - if (in_array($protocol, ['gs', 'gcs'])) { - $bucket = array_shift($urlParts); - $files[$mediaFileName] = [ - '@type' => 'file', - '@location' => 'gcs', - 'bucket' => $bucket, - 'object' => implode('/', $urlParts), - ]; - } elseif ('sfs-media-filesystem' === $protocol) { - $fileName = array_pop($urlParts); - $files[$mediaFileName] = [ - '@type' => 'file', - '@location' => 'sfs-media-filesystem', - 'path' => $this->mediaStoragePath.'/'.implode('/', $urlParts), - 'object' => $fileName, - ]; - } else { - throw new Exception(sprintf('Media %s protocol not supported for url %s', $protocol, $url)); - } - - $files['media/'.$data->getId().'.json'] = [ - '@type' => 'json', - 'json' => [ - 'id' => $data->getId(), - 'type' => $data->getType(), - 'media_type' => $data->getMediaType(), - 'name' => $data->getName(), - 'description' => $data->getDescription(), - 'versionFiles' => $versionFiles, - ], - ]; - - return [ - '_reference' => 'media___'.$data->getId(), - ]; - } - - public function supportsImport(string $type, mixed $data): bool - { - return isset($data['_reference']) && str_starts_with($data['_reference'], 'media___'); - } - - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options = []): mixed - { - return $referencesRepository->getReference($data['_reference'], true); - } -} diff --git a/src/Data/FieldTransformer/RouteFieldTransformer.php b/src/Data/FieldTransformer/RouteFieldTransformer.php deleted file mode 100644 index f3b4dc1d..00000000 --- a/src/Data/FieldTransformer/RouteFieldTransformer.php +++ /dev/null @@ -1,39 +0,0 @@ - 'route___'.$data->getId(), - ]; - } - - public function supportsImport(string $type, mixed $data): bool - { - return isset($data['_reference']) && str_starts_with($data['_reference'], 'route___'); - } - - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options = []): mixed - { - return $referencesRepository->getReference($data['_reference'], true); - } -} diff --git a/src/Data/FieldTransformer/SiteFieldTransformer.php b/src/Data/FieldTransformer/SiteFieldTransformer.php deleted file mode 100644 index 591c3fae..00000000 --- a/src/Data/FieldTransformer/SiteFieldTransformer.php +++ /dev/null @@ -1,40 +0,0 @@ - 'site___'.Slugger::lowerSlug($data->getId()), - ]; - } - - public function supportsImport(string $type, mixed $data): bool - { - return isset($data['_reference']) && str_starts_with($data['_reference'], 'site___'); - } - - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options = []): mixed - { - return $referencesRepository->getReference($data['_reference'], true); - } -} diff --git a/src/Data/FieldTransformer/TranslationFieldTransformer.php b/src/Data/FieldTransformer/TranslationFieldTransformer.php deleted file mode 100644 index ef02831b..00000000 --- a/src/Data/FieldTransformer/TranslationFieldTransformer.php +++ /dev/null @@ -1,45 +0,0 @@ -__toArray(); - } - - public function supportsImport(string $type, mixed $data): bool - { - return isset($data['_trans_id']); - } - - /** - * @param array $data - * @return Translation - */ - public function import(mixed $data, ReferencesRepository $referencesRepository, array $options = []): mixed - { - return Translation::createFromArray($data); - } -} diff --git a/src/Data/ReferencesRepository.php b/src/Data/ReferencesRepository.php deleted file mode 100644 index f686d4f6..00000000 --- a/src/Data/ReferencesRepository.php +++ /dev/null @@ -1,32 +0,0 @@ -references[$id] = $entity; - } - - /** - * @throws ReferenceNotFoundException - */ - public function getReference(string $id, bool $throwNotFound = false): ?object - { - $entity = $this->references[$id] ?? null; - - if (!$entity && $throwNotFound) { - throw new ReferenceNotFoundException("Reference $id not found"); - } - - return $entity; - } -} diff --git a/src/DataFixtures/CmsFixtures.php b/src/DataFixtures/CmsFixtures.php deleted file mode 100644 index 69e774b2..00000000 --- a/src/DataFixtures/CmsFixtures.php +++ /dev/null @@ -1,83 +0,0 @@ -container = $container; - $this->dataImporter = $dataImporter; - $this->fixturesPath = $this->container->getParameter('kernel.project_dir').'/cms/fixtures'; - $this->cmsLogger = $cmsLogger; - } - - protected function readFixtures(): array - { - $contents = []; - - foreach (['contents', 'routes', 'blocks', 'menus'] as $type) { - if (is_dir("$this->fixturesPath/$type")) { - foreach ((new Finder())->in("$this->fixturesPath/$type")->files() as $contentFile) { - $this->cmsLogger && $this->cmsLogger->debug(sprintf('Fixture "%s/%s" found', $contentFile->getPath(), $contentFile->getFilename())); - - $data = Yaml::parseFile($contentFile->getRealPath()); - $id = $contentFile->getFilenameWithoutExtension(); - $contents[$type][$id] = $data; - } - } - } - - if (is_dir("$this->fixturesPath/media")) { - foreach ((new Finder())->in("$this->fixturesPath/media")->files()->name('*.json') as $mediaConfig) { - $this->cmsLogger && $this->cmsLogger->debug(sprintf('Media "%s/%s" found', $mediaConfig->getPath(), $mediaConfig->getFilename())); - - $data = json_decode(file_get_contents($mediaConfig->getRealPath()), true); - $id = $mediaConfig->getFilenameWithoutExtension(); - $contents['media'][$id] = [ - 'media' => $data, - 'files' => [], - ]; - - $contents['media'][$id]['media']['versionFiles'] = array_map(fn ($name): string|array => str_ireplace($this->fixturesPath.'/', '', $name), $contents['media'][$id]['media']['versionFiles']); - - foreach ((new Finder())->in("$this->fixturesPath/media")->files()->name("{$data['id']}.*")->notName('*.json') as $mediaFile) { - $contents['media'][$id]['files']["media/{$mediaFile->getFilename()}"] = [ - 'name' => $mediaFile->getFilename(), - 'path' => "media/{$mediaFile->getFilename()}", - 'size' => $mediaFile->getSize(), - 'tmpPath' => $mediaFile->getRealPath(), - ]; - } - } - } - - return $contents; - } - - public function load(ObjectManager $manager): void - { - $manager->clear(); - $this->dataImporter->import($this->readFixtures(), ['version_origin' => ContentVersionInterface::ORIGIN_FIXTURE, 'auto_publish_version' => true]); - } - - public static function getGroups(): array - { - return ['sfs_cms']; - } -} diff --git a/src/DataFixtures/Purger/CmsPurger.php b/src/DataFixtures/Purger/CmsPurger.php deleted file mode 100644 index 88864b61..00000000 --- a/src/DataFixtures/Purger/CmsPurger.php +++ /dev/null @@ -1,303 +0,0 @@ -em = $em; - $this->excluded = $excluded; - } - - /** - * Set the purge mode. - */ - public function setPurgeMode(int $mode): void - { - $this->purgeMode = $mode; - } - - /** - * Get the purge mode. - */ - public function getPurgeMode(): int - { - return $this->purgeMode; - } - - public function setEntityManager(EntityManagerInterface $em): void - { - $this->em = $em; - } - - /** - * Retrieve the EntityManagerInterface instance this purger instance is using. - */ - public function getObjectManager(): ?EntityManagerInterface - { - return $this->em; - } - - public function purge(): void - { - $classes = []; - - foreach ($this->em->getMetadataFactory()->getAllMetadata() as $metadata) { - if ($metadata->isMappedSuperclass || (null !== $metadata->isEmbeddedClass && $metadata->isEmbeddedClass)) { - continue; - } - - $classes[] = $metadata; - } - - $commitOrder = $this->getCommitOrder($this->em, $classes); - - // Get platform parameters - $platform = $this->em->getConnection()->getDatabasePlatform(); - - // Drop association tables first - $orderedTables = $this->getAssociationTables($commitOrder, $platform); - - // Drop tables in reverse commit order - for ($i = \count($commitOrder) - 1; $i >= 0; --$i) { - $class = $commitOrder[$i]; - - if ( - (null !== $class->isEmbeddedClass && $class->isEmbeddedClass) - || $class->isMappedSuperclass - || ($class->isInheritanceTypeSingleTable() && $class->name !== $class->rootEntityName) - ) { - continue; - } - - $orderedTables[] = $this->getTableName($class, $platform); - } - - $connection = $this->em->getConnection(); - $filterExpr = \method_exists( - $connection->getConfiguration(), - 'getFilterSchemaAssetsExpression' - ) ? $connection->getConfiguration()->getFilterSchemaAssetsExpression() : null; - $emptyFilterExpression = empty($filterExpr); - - $schemaAssetsFilter = \method_exists( - $connection->getConfiguration(), - 'getSchemaAssetsFilter' - ) ? $connection->getConfiguration()->getSchemaAssetsFilter() : null; - - $this->disableForeignKeyChecksForMySQL($connection); - - foreach ($orderedTables as $tbl) { - // If we have a filter expression, check it and skip if necessary - if (!$emptyFilterExpression && !\preg_match($filterExpr, $tbl)) { - continue; - } - - // If the table is excluded, skip it as well - if (in_array($tbl, $this->excluded)) { - continue; - } - - // Support schema asset filters as presented in - if (\is_callable($schemaAssetsFilter) && !$schemaAssetsFilter($tbl)) { - continue; - } - - if (self::PURGE_MODE_DELETE === $this->purgeMode) { - $connection->executeStatement($this->getDeleteFromTableSQL($tbl, $platform)); - } else { - $connection->executeStatement($platform->getTruncateTableSQL($tbl, true)); - } - } - - $this->enableForeignKeyChecksForMySQL($connection); - } - - /** - * @param ClassMetadata[] $classes - * - * @return ClassMetadata[] - */ - private function getCommitOrder(EntityManagerInterface $em, array $classes): array - { - $sorter = new TopologicalSorter(); - - foreach ($classes as $class) { - if (!$sorter->hasNode($class->name)) { - $sorter->addNode($class->name, $class); - } - - // $class before its parents - foreach ($class->parentClasses as $parentClass) { - $parentClass = $em->getClassMetadata($parentClass); - $parentClassName = $parentClass->getName(); - - if (!$sorter->hasNode($parentClassName)) { - $sorter->addNode($parentClassName, $parentClass); - } - - $sorter->addDependency($class->name, $parentClassName); - } - - foreach ($class->associationMappings as $assoc) { - if (!$assoc['isOwningSide']) { - continue; - } - - $targetClass = $em->getClassMetadata($assoc['targetEntity']); - \assert($targetClass instanceof ClassMetadata); - $targetClassName = $targetClass->getName(); - - if (!$sorter->hasNode($targetClassName)) { - $sorter->addNode($targetClassName, $targetClass); - } - - // add dependency ($targetClass before $class) - $sorter->addDependency($targetClassName, $class->name); - - // parents of $targetClass before $class, too - foreach ($targetClass->parentClasses as $parentClass) { - $parentClass = $em->getClassMetadata($parentClass); - $parentClassName = $parentClass->getName(); - - if (!$sorter->hasNode($parentClassName)) { - $sorter->addNode($parentClassName, $parentClass); - } - - $sorter->addDependency($parentClassName, $class->name); - } - } - } - - return \array_reverse($sorter->sort()); - } - - /** - * @param ClassMetadata[] $classes - * - * @return string[] - */ - private function getAssociationTables(array $classes, AbstractPlatform $platform): array - { - $associationTables = []; - - foreach ($classes as $class) { - foreach ($class->associationMappings as $assoc) { - if (!$assoc['isOwningSide'] || ClassMetadata::MANY_TO_MANY !== $assoc['type']) { - continue; - } - - $associationTables[] = $this->getJoinTableName($assoc, $class, $platform); - } - } - - return $associationTables; - } - - private function getTableName(ClassMetadata $class, AbstractPlatform $platform): string - { - if (isset($class->table['schema']) && !\method_exists($class, 'getSchemaName')) { - return $class->table['schema'].'.'. - $this->em->getConfiguration() - ->getQuoteStrategy() - ->getTableName($class, $platform); - } - - return $this->em->getConfiguration()->getQuoteStrategy()->getTableName($class, $platform); - } - - private function getJoinTableName( - AssociationMapping $assoc, - ClassMetadata $class, - AbstractPlatform $platform, - ): string { - if (isset($assoc['joinTable']['schema']) && !\method_exists($class, 'getSchemaName')) { - return $assoc['joinTable']['schema'].'.'. - $this->em->getConfiguration() - ->getQuoteStrategy() - ->getJoinTableName($assoc, $class, $platform); - } - - return $this->em->getConfiguration()->getQuoteStrategy()->getJoinTableName($assoc, $class, $platform); - } - - private function getDeleteFromTableSQL(string $tableName, AbstractPlatform $platform): string - { - $tableIdentifier = new Identifier($tableName); - - return 'DELETE FROM '.$tableIdentifier->getQuotedName($platform); - } - - private function disableForeignKeyChecksForMySQL(Connection $connection): void - { - if (!$this->isMySQL($connection)) { - return; - } - - // see MySQL TRUNCATE TABLE Statement: fails for an InnoDB or NDB table - // if there are any FOREIGN KEY constraints from other tables that - // reference the table. - $connection->executeStatement('SET @DOCTRINE_OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS'); - $connection->executeStatement('SET FOREIGN_KEY_CHECKS = 0'); - } - - private function enableForeignKeyChecksForMySQL(Connection $connection): void - { - if (!$this->isMySQL($connection)) { - return; - } - - $connection->executeStatement('SET FOREIGN_KEY_CHECKS = @DOCTRINE_OLD_FOREIGN_KEY_CHECKS'); - } - - private function isMySQL(Connection $connection): bool - { - $platform = $connection->getDatabasePlatform(); - - if (!class_exists(AbstractMySQLPlatform::class)) { - // before DBAL 3.3 - return $platform instanceof MySQLPlatform; - } - - return $platform instanceof AbstractMySQLPlatform; - } -} diff --git a/src/DataFixtures/Purger/CmsPurgerFactory.php b/src/DataFixtures/Purger/CmsPurgerFactory.php deleted file mode 100644 index 64fa2c04..00000000 --- a/src/DataFixtures/Purger/CmsPurgerFactory.php +++ /dev/null @@ -1,28 +0,0 @@ -getConnection()->fetchAllAssociative('SHOW TABLES'); - - foreach ($tables as $table) { - $table = current($table); - - if (!str_starts_with($table, 'cms_')) { - $excluded[] = $table; - } - } - - $purger = new CmsPurger($em, $excluded); - $purger->setPurgeMode($purgeWithTruncate ? CmsPurger::PURGE_MODE_TRUNCATE : CmsPurger::PURGE_MODE_DELETE); - - return $purger; - } -} diff --git a/src/DependencyInjection/SfsCmsExtension.php b/src/DependencyInjection/SfsCmsExtension.php index 7d5df530..0faa4e51 100644 --- a/src/DependencyInjection/SfsCmsExtension.php +++ b/src/DependencyInjection/SfsCmsExtension.php @@ -4,8 +4,6 @@ use Composer\InstalledVersions; use Softspring\CmsBundle\Config\ConfigLoader; -use Softspring\CmsBundle\Data\EntityTransformer\EntityTransformerInterface; -use Softspring\CmsBundle\Data\FieldTransformer\FieldTransformerInterface; use Softspring\CmsBundle\Entity\Block; use Softspring\CmsBundle\Entity\CompiledData; use Softspring\CmsBundle\Entity\Content; @@ -30,10 +28,6 @@ class SfsCmsExtension extends Extension implements PrependExtensionInterface { public function load(array $configs, ContainerBuilder $container): void { - /* @deprecated will be removed on 6.0 version, when fixtures will be refactored to use serializer */ - $container->registerForAutoconfiguration(EntityTransformerInterface::class)->addTag('sfs_cms.data.entity_transformer'); - $container->registerForAutoconfiguration(FieldTransformerInterface::class)->addTag('sfs_cms.data.field_transformer'); - $processor = new Processor(); $configuration = new Configuration(); $config = $processor->processConfiguration($configuration, $configs); diff --git a/src/Form/Admin/Content/ContentImportForm.php b/src/Form/Admin/Content/ContentImportForm.php deleted file mode 100644 index 185ee9bd..00000000 --- a/src/Form/Admin/Content/ContentImportForm.php +++ /dev/null @@ -1,39 +0,0 @@ -setDefaults([ - 'validation_groups' => ['Default', 'import'], - 'translation_domain' => 'sfs_cms_contents', - 'content_config' => null, - ]); - - $resolver->setNormalizer('label_format', function (Options $options, $value): string { - return "admin_{$options['content_config']['_id']}.import.form.%name%.label"; - }); - } - - public function buildForm(FormBuilderInterface $builder, array $options): void - { - // TODO CHECK ALLOWED CONTENT TYPE - - $builder->add('file', FileType::class, [ - 'constraints' => [ - new NotBlank(), - new ContentZipFile(), - ], - ]); - } -} diff --git a/src/Form/Admin/Content/ContentImportFormInterface.php b/src/Form/Admin/Content/ContentImportFormInterface.php deleted file mode 100644 index e8e517f0..00000000 --- a/src/Form/Admin/Content/ContentImportFormInterface.php +++ /dev/null @@ -1,9 +0,0 @@ -setDefaults([ - 'validation_groups' => ['Default', 'import_version'], - 'translation_domain' => 'sfs_cms_contents', - 'content_config' => null, - ]); - - $resolver->setNormalizer('label_format', function (Options $options, $value): string { - return "admin_{$options['content_config']['_id']}.import_version.form.%name%.label"; - }); - } - - public function buildForm(FormBuilderInterface $builder, array $options): void - { - $builder->add('file', FileType::class, [ - 'constraints' => [ - new NotBlank(), - new ContentZipFile(), - ], - ]); - } -} diff --git a/src/Form/Admin/ContentVersion/VersionImportFormInterface.php b/src/Form/Admin/ContentVersion/VersionImportFormInterface.php deleted file mode 100644 index ad1b47a2..00000000 --- a/src/Form/Admin/ContentVersion/VersionImportFormInterface.php +++ /dev/null @@ -1,9 +0,0 @@ - {% endif %} + {% if route_defined('sfs_cms_admin_content_'~content_type~'_export_version') %} + {# TODO make this configurable and extensible for plugins #} {% if not content_config.admin.export_version.is_granted or is_granted(content_config.admin.export_version.is_granted, version) %} {{ ('admin_'~content_type~'.versions.actions.export.link')|trans }} {% endif %} + {% endif %} {% if not content_config.admin.publish_version.is_granted or is_granted(content_config.admin.publish_version.is_granted, version) %} {% if not version.published %} diff --git a/templates/admin/content/delete.html.twig b/templates/admin/content/delete.html.twig index 4db0eb6b..4db5a855 100644 --- a/templates/admin/content/delete.html.twig +++ b/templates/admin/content/delete.html.twig @@ -31,10 +31,13 @@ {% if entity.publishedVersion|default(entity.lastVersion) %}

{{ ('admin_'~content_type~'.delete.offer_backup')|trans }}

-
- - {{ ('admin_'~content_type~'.delete.actions.export.button')|trans }} -
+ {% if route_defined('sfs_cms_admin_content_'~content_type~'_export_version') %} + {# TODO make this configurable and extensible for plugins #} +
+ + {{ ('admin_'~content_type~'.delete.actions.export.button')|trans }} +
+ {% endif %} {% endif %} {{ ('admin_'~content_type~'.delete.index_warnings_raw')|trans|raw }} diff --git a/templates/admin/content/import.html.twig b/templates/admin/content/import.html.twig deleted file mode 100644 index 5b121d27..00000000 --- a/templates/admin/content/import.html.twig +++ /dev/null @@ -1,35 +0,0 @@ -{% trans_default_domain 'sfs_cms_contents' %} - -{% extends '@SfsCms/admin_layout.html.twig' %} - -{% form_theme form - '@SfsCms/forms/cms_theme.html.twig' - '@SfsCms/forms/routes_theme.html.twig' - '@SfsCms/forms/types_theme.html.twig' -%} - -{% block title %}{{ ('admin_'~content_type~'.import.meta.title')|trans }}{% endblock %} - -{% block breadcrums_content %} - {{ parent() }} - - -{% endblock breadcrums_content %} - -{% block content %} -

{{ ('admin_'~content_type~'.import.title')|trans }}

- -
- {{ form_start(form) }} - {# {{ form_row(form.name) }}#} - {# {{ form_row(form.site) }}#} - {# {{ form_row(form.routes) }}#} - {{ form_rest(form) }} - -
- {{ ('admin_'~content_type~'.import.actions.cancel.button')|trans }} - -
- {{ form_end(form) }} -
-{% endblock content %} diff --git a/templates/admin/content/import_version.html.twig b/templates/admin/content/import_version.html.twig deleted file mode 100644 index ca4d79f3..00000000 --- a/templates/admin/content/import_version.html.twig +++ /dev/null @@ -1,2 +0,0 @@ -{% deprecated 'The import_version.html.twig template is deprecated, use version_import.html.twig' %} -{% extends '@SfsCms/admin/content/version_import.html.twig' %} \ No newline at end of file diff --git a/templates/admin/content/list.html.twig b/templates/admin/content/list.html.twig index 69feaab0..9d6994fd 100644 --- a/templates/admin/content/list.html.twig +++ b/templates/admin/content/list.html.twig @@ -17,8 +17,11 @@ {{ ('admin_'~content_type~'.list.actions.create.link')|trans }} {% endif %} - {% if not content_config.admin.import.is_granted or is_granted(content_config.admin.import.is_granted) %} - {{ ('admin_'~content_type~'.list.actions.import.link')|trans }} + {% if route_defined('sfs_cms_admin_content_'~content_type~'_import') %} + {# TODO make this configurable and extensible for plugins #} + {% if not content_config.admin.import.is_granted or is_granted(content_config.admin.import.is_granted) %} + {{ ('admin_'~content_type~'.list.actions.import.link')|trans }} + {% endif %} {% endif %} @@ -75,6 +78,7 @@ '%create_link%': url('sfs_cms_admin_content_'~content_type~'_create'), '%import_link%': url('sfs_cms_admin_content_'~content_type~'_import'), })|raw }} + {# TODO IMPORT LINK DOES NOT ALWAYS EXIST #} {% else %} {{ ('admin_'~content_type~'.list.empty.can_not_create_content')|trans }} {% endif %} diff --git a/templates/admin/content/version_delete.html.twig b/templates/admin/content/version_delete.html.twig index 45531037..d0c08959 100644 --- a/templates/admin/content/version_delete.html.twig +++ b/templates/admin/content/version_delete.html.twig @@ -29,10 +29,13 @@

{{ ('admin_'~content_type~'.version_delete.offer_backup')|trans }}

+ {% if route_defined('sfs_cms_admin_content_'~content_type~'_export_version') %} + {# TODO make this configurable and extensible for plugins #}
{{ ('admin_'~content_type~'.version_delete.actions.export.button')|trans }}
+ {% endif %} {{ form_rest(form) }} diff --git a/templates/admin/content/version_import.html.twig b/templates/admin/content/version_import.html.twig deleted file mode 100644 index 95797629..00000000 --- a/templates/admin/content/version_import.html.twig +++ /dev/null @@ -1,43 +0,0 @@ -{% trans_default_domain 'sfs_cms_contents' %} - -{% extends '@SfsCms/admin_layout.html.twig' %} - -{% form_theme form - '@SfsCms/forms/cms_theme.html.twig' - '@SfsCms/forms/routes_theme.html.twig' - '@SfsCms/forms/types_theme.html.twig' -%} - -{% block title %}{{ ('admin_'~content_type~'.import_version.meta.title')|trans({'%name%':entity.name}) }}{% endblock %} - -{% block breadcrums_content %} - {{ parent() }} - - - - -{% endblock breadcrums_content %} - -{% block content %} - {% include ['@content/'~content_type~'/admin/_content_title.html.twig', '@SfsCms/admin/content/_content_title.html.twig'] with {'current':'versions', 'content_type':content_type, 'content_entity':entity} %} - {% include ['@content/'~content_type~'/admin/_content_tabs.html.twig', '@SfsCms/admin/content/_content_tabs.html.twig'] with {'current':'versions', 'content_entity':entity} %} - -
-
-

{{ ('admin_'~content_type~'.import_version.title')|trans({'%name%':entity.name}) }}

- - {{ form_start(form) }} - {{ form_errors(form) }} - - - {{ form_rest(form) }} - - - {{ form_end(form) }} -
-
- -{% endblock content %} diff --git a/templates/admin/content/version_info.html.twig b/templates/admin/content/version_info.html.twig index 19df4381..72c5b586 100644 --- a/templates/admin/content/version_info.html.twig +++ b/templates/admin/content/version_info.html.twig @@ -44,11 +44,14 @@ {% endif %} + {% if route_defined('sfs_cms_admin_content_'~content_type~'_export_version') %} + {# TODO make this configurable and extensible for plugins #} {% if not content_config.admin.export_version.is_granted or is_granted(content_config.admin.export_version.is_granted, version) %} {{ ('admin_'~content_type~'.versions.actions.export.link')|trans }} {% endif %} + {% endif %}