|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Neusta\Pimcore\ImportExportBundle\Controller\Admin; |
| 6 | + |
| 7 | +use Neusta\Pimcore\ImportExportBundle\Documents\Import\PageImporter; |
| 8 | +use Neusta\Pimcore\ImportExportBundle\Toolbox\Repository\PageRepository; |
| 9 | +use Pimcore\Model\Document\Page; |
| 10 | +use Symfony\Component\HttpFoundation\File\UploadedFile; |
| 11 | +use Symfony\Component\HttpFoundation\JsonResponse; |
| 12 | +use Symfony\Component\HttpFoundation\Request; |
| 13 | +use Symfony\Component\Routing\Annotation\Route; |
| 14 | + |
| 15 | +final class PageImportController |
| 16 | +{ |
| 17 | + public function __construct( |
| 18 | + private PageImporter $pageImporter, |
| 19 | + private PageRepository $pageRepository, |
| 20 | + ) { |
| 21 | + } |
| 22 | + |
| 23 | + #[Route( |
| 24 | + '/admin/neusta/import-export/page/import', |
| 25 | + name: 'neusta_pimcore_import_export_page_import', |
| 26 | + methods: ['POST'] |
| 27 | + )] |
| 28 | + public function import(Request $request): JsonResponse |
| 29 | + { |
| 30 | + $file = $request->files->get('file'); |
| 31 | + if (!$file instanceof UploadedFile) { |
| 32 | + return new JsonResponse(['success' => false, 'message' => 'No file uploaded'], 400); |
| 33 | + } |
| 34 | + |
| 35 | + $overwrite = $request->request->getBoolean('overwrite'); |
| 36 | + |
| 37 | + try { |
| 38 | + $page = $this->pageImporter->parseYaml($file->getContent()); |
| 39 | + |
| 40 | + $message = $this->replaceIfExists($page, $overwrite); |
| 41 | + |
| 42 | + return new JsonResponse(['success' => true, 'message' => $message]); |
| 43 | + } catch (\Exception $e) { |
| 44 | + return new JsonResponse(['success' => false, 'message' => $e->getMessage()], 500); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + protected function replaceIfExists(Page $page, bool $overwrite): string |
| 49 | + { |
| 50 | + $oldPage = $this->pageRepository->getByPath('/' . $page->getFullPath()); |
| 51 | + if (null !== $oldPage) { |
| 52 | + if ($overwrite) { |
| 53 | + $oldPage->delete(); |
| 54 | + $page->save(); |
| 55 | + |
| 56 | + return 'Document replaced successfully'; |
| 57 | + } |
| 58 | + |
| 59 | + return 'Document already exists and was not replaced'; |
| 60 | + } |
| 61 | + $page->save(); |
| 62 | + |
| 63 | + return 'New Document imported successfully'; |
| 64 | + } |
| 65 | +} |
0 commit comments