From 621b8f81ba72023b05ddecac3f64681dad117645 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Wed, 11 Mar 2026 12:31:36 +0100 Subject: [PATCH] process base64 payload in menu to create twig templates on server --- CHANGELOG.md | 7 + src/Controller/MenuBrowserController.php | 2 +- src/Dto/Input/MenuInput.php | 4 + src/State/Processor/MenuProcessor.php | 176 ++++++++++++++++++++++- 4 files changed, 185 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db719f5..2fc644e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,11 @@ # Changelog +## [1.2.3] - 2026-03-11 +### Added +- Se ha añadido una nueva funcionalidad en el DTO `MenuInput` (campo `menuHtmlContent`) para recibir la plantilla HTML íntegra del menú codificada en Base64. + +### Improved +- Se ha refactorizado y asegurado la lógica de creación de menús dentro de `MenuProcessor`, para decodificar estrictamente el payload en Base64 y sobreescribir físicamente la plantilla `.twig` descartando la plantilla por defecto. + ## [1.2.2] - 2026-02-27 ### Improved - Nuevo menú por defecto en el cliente, organizando la información por discos diff --git a/src/Controller/MenuBrowserController.php b/src/Controller/MenuBrowserController.php index 0553a91..4d661f1 100644 --- a/src/Controller/MenuBrowserController.php +++ b/src/Controller/MenuBrowserController.php @@ -76,7 +76,7 @@ class MenuBrowserController extends AbstractController ]); } - #[Route('/menu/{templateName}', name: 'render_menu_template')] + #[Route('/menu/{templateName}', name: 'render_menu_template', requirements: ['templateName' => '.+'])] public function renderMenu(string $templateName, Request $request): Response { $templatePath = 'browser/' . $templateName . '.html.twig'; diff --git a/src/Dto/Input/MenuInput.php b/src/Dto/Input/MenuInput.php index 5a8c1c1..9835a73 100644 --- a/src/Dto/Input/MenuInput.php +++ b/src/Dto/Input/MenuInput.php @@ -37,6 +37,10 @@ final class MenuInput #[ApiProperty(description: 'The default menu', example: "false")] public ?bool $isDefault = false; + #[Groups(['menu:write'])] + #[ApiProperty(description: 'HTML Content of the menu in Base64', example: "PGh0bWw+PC9odG1sPg==")] + public ?string $menuHtmlContent = null; + public function __construct(?Menu $menu = null) { if (!$menu) { diff --git a/src/State/Processor/MenuProcessor.php b/src/State/Processor/MenuProcessor.php index a0722c2..ff9576c 100644 --- a/src/State/Processor/MenuProcessor.php +++ b/src/State/Processor/MenuProcessor.php @@ -12,12 +12,19 @@ use ApiPlatform\Validator\ValidatorInterface; use App\Dto\Input\MenuInput; use App\Dto\Output\MenuOutput; use App\Repository\MenuRepository; +use App\Entity\Menu; +use Symfony\Component\Filesystem\Exception\IOExceptionInterface; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; +use Symfony\Component\Filesystem\Filesystem; + readonly class MenuProcessor implements ProcessorInterface { public function __construct( private MenuRepository $menuRepository, - private ValidatorInterface $validator + private ValidatorInterface $validator, + private ParameterBagInterface $params, + private Filesystem $filesystem ) { } @@ -47,12 +54,24 @@ readonly class MenuProcessor implements ProcessorInterface } $entity = null; + $oldPublicUrl = null; + if (isset($uriVariables['uuid'])) { $entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']); + if ($entity) { + $oldPublicUrl = $entity->getPublicUrl(); + } } $menu = $data->createOrUpdateEntity($entity); $this->validator->validate($menu); + + // Extraemos el contenido base64 (asumiendo que $data es tu MenuInput) + $base64HtmlContent = property_exists($data, 'menuHtmlContent') ? $data->menuHtmlContent : null; + + // Sincronización de ficheros físicos y caché + $this->syncMenuTemplateFile($menu, $operation, $oldPublicUrl, $base64HtmlContent); + $this->menuRepository->save($menu); return new MenuOutput($menu); @@ -60,9 +79,160 @@ readonly class MenuProcessor implements ProcessorInterface private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null { - $user = $this->menuRepository->findOneByUuid($uriVariables['uuid']); - $this->menuRepository->delete($user); + $entity = null; + + if (isset($uriVariables['uuid'])) { + $entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']); + + if ($entity) { + // 1. Borrar el fichero físico y la caché antes de eliminar de BD + $this->removeMenuTemplateFile($entity); + + // 2. Eliminar de la base de datos + $this->menuRepository->delete($entity); + } + } return null; } + + /** + * Creates, renames, and updates the Twig file associated with the menu. + * Throws \RuntimeException if any file system operation fails. + */ + private function syncMenuTemplateFile(Menu $menu, Operation $operation, ?string $oldPublicUrl, ?string $base64HtmlContent = null): void + { + $newPublicUrl = $menu->getPublicUrl(); + + if ($newPublicUrl) { + $projectDir = $this->params->get('kernel.project_dir'); + $templatesDir = rtrim($projectDir, '/') . '/templates/browser/'; + $newTemplateName = preg_replace('#^/menu/#', '', parse_url($newPublicUrl, PHP_URL_PATH)); + + if (!empty($newTemplateName)) { + $targetFile = $templatesDir . $newTemplateName . '.html.twig'; + $filesChanged = false; + + try { + // 1. RENAME OPERATION (Only for PUT/PATCH if URL changed) + if (($operation instanceof Put || $operation instanceof Patch) && $newPublicUrl !== $oldPublicUrl && $oldPublicUrl) { + $oldTemplateName = preg_replace('#^/menu/#', '', parse_url($oldPublicUrl, PHP_URL_PATH)); + $sourceFile = $templatesDir . $oldTemplateName . '.html.twig'; + + if ($this->filesystem->exists($sourceFile)) { + $this->filesystem->mkdir(dirname($targetFile), 0755); + $this->filesystem->rename($sourceFile, $targetFile, true); + $this->cleanupEmptyDirectories(dirname($sourceFile), $templatesDir); + $filesChanged = true; + } + } + + // 2. DETERMINE CONTENT + $contentToWrite = "{# Template for menu: {$menu->getName()} #}\n{% extends 'base.html.twig' %}\n{% block body %}\n

{$menu->getName()}

\n{% endblock %}\n"; + $hasCustomContent = false; + + if (!empty($base64HtmlContent)) { + $decodedContent = base64_decode($base64HtmlContent, true); // true = strict mode + if ($decodedContent !== false) { + $contentToWrite = $decodedContent; + $hasCustomContent = true; + } + } + + // 3. WRITE OPERATION (If file doesn't exist, OR if we received explicit HTML content) + if (!$this->filesystem->exists($targetFile) || $hasCustomContent) { + $this->filesystem->mkdir(dirname($targetFile), 0755); + $this->filesystem->dumpFile($targetFile, $contentToWrite); + + $filesChanged = true; + } + + // 4. TWIG CACHE INVALIDATION + if ($filesChanged) { + $env = $this->params->get('kernel.environment'); + $twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig'; + + if ($this->filesystem->exists($twigCacheDir)) { + $this->filesystem->remove($twigCacheDir); + } + } + } catch (IOExceptionInterface $exception) { + throw new \RuntimeException( + sprintf('Critical failure synchronizing menu template file. Reason: %s', $exception->getMessage()), + 0, + $exception + ); + } + } + } + } + + /** + * Removes the Twig file associated with the menu, cleans up empty parent directories, + * and clears the cache. Throws \RuntimeException if any file system operation fails. + */ + private function removeMenuTemplateFile(Menu $menu): void + { + $publicUrl = $menu->getPublicUrl(); + + if ($publicUrl) { + $projectDir = $this->params->get('kernel.project_dir'); + $templatesDir = $projectDir . '/templates/browser/'; + $templateName = preg_replace('#^/menu/#', '', parse_url($publicUrl, PHP_URL_PATH)); + + if (!empty($templateName)) { + $targetFile = $templatesDir . $templateName . '.html.twig'; + + try { + if ($this->filesystem->exists($targetFile)) { + // 1. Delete the actual file + $this->filesystem->remove($targetFile); + + $this->cleanupEmptyDirectories(dirname($targetFile), $templatesDir); + + // 3. TWIG CACHE INVALIDATION + $env = $this->params->get('kernel.environment'); + $twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig'; + + if ($this->filesystem->exists($twigCacheDir)) { + $this->filesystem->remove($twigCacheDir); + } + } + } catch (IOExceptionInterface $exception) { + throw new \RuntimeException( + sprintf('Critical failure removing menu template file or directories. Reason: %s', $exception->getMessage()), 0, $exception); + } + } + } + } + + /** + * Traverses upwards from a starting directory to a base directory, removing empty folders. + */ + private function cleanupEmptyDirectories(string $startDir, string $baseDir): void + { + $currentDir = $startDir; + $baseDirExact = rtrim($baseDir, '/'); + $continueCleaning = true; + + // La condición del while tiene el control absoluto del flujo + while ($continueCleaning && $currentDir !== $baseDirExact && str_starts_with($currentDir, $baseDirExact)) { + // Asumimos que pararemos, a menos que encontremos una carpeta vacía + $continueCleaning = false; + + if (is_dir($currentDir)) { + $dirContents = array_diff(scandir($currentDir), ['.', '..']); + + if (empty($dirContents)) { + $this->filesystem->remove($currentDir); + $currentDir = dirname($currentDir); + + // Como hemos borrado esta, le decimos al bucle que siga mirando arriba + $continueCleaning = true; + } + } + } + } + + }