Skip to content

Commit

Permalink
refactor: Removed base RozierApp class when possible, added LogTrail …
Browse files Browse the repository at this point in the history
…service for publishing message in session and logger
  • Loading branch information
ambroisemaupate committed Dec 3, 2024
1 parent acb892a commit 539806d
Show file tree
Hide file tree
Showing 33 changed files with 500 additions and 893 deletions.
37 changes: 7 additions & 30 deletions lib/RoadizCompatBundle/src/Controller/AppController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
use RZ\Roadiz\CompatBundle\Theme\ThemeResolverInterface;
use RZ\Roadiz\CoreBundle\Entity\Theme;
use RZ\Roadiz\CoreBundle\Exception\ThemeClassNotValidException;
use RZ\Roadiz\CoreBundle\Security\LogTrail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\String\UnicodeString;
use Twig\Error\LoaderError;
Expand Down Expand Up @@ -248,37 +248,12 @@ public function getTheme(): ?Theme
/**
* Publish a confirmation message in Session flash bag and
* logger interface.
*
* @deprecated Use LogTrail instead
*/
public function publishConfirmMessage(Request $request, string $msg, ?object $source = null): void
{
$this->publishMessage($request, $msg, 'confirm', $source);
}

/**
* Publish a message in Session flash bag and
* logger interface.
*/
protected function publishMessage(
Request $request,
string $msg,
string $level = 'confirm',
?object $source = null,
): void {
$session = $this->getSession($request);
if ($session instanceof Session) {
$session->getFlashBag()->add($level, $msg);
}

switch ($level) {
case 'error':
case 'danger':
case 'fail':
$this->getLogger()->error($msg, ['entity' => $source]);
break;
default:
$this->getLogger()->info($msg, ['entity' => $source]);
break;
}
$this->container->get(LogTrail::class)->publishConfirmMessage($request, $msg, $source);
}

/**
Expand All @@ -294,10 +269,12 @@ public function getSession(?Request $request = null): ?SessionInterface
/**
* Publish an error message in Session flash bag and
* logger interface.
*
* @deprecated Use LogTrail instead
*/
public function publishErrorMessage(Request $request, string $msg, ?object $source = null): void
{
$this->publishMessage($request, $msg, 'error', $source);
$this->container->get(LogTrail::class)->publishErrorMessage($request, $msg, $source);
}

/**
Expand Down
8 changes: 7 additions & 1 deletion lib/RoadizCompatBundle/src/Controller/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use RZ\Roadiz\CoreBundle\SearchEngine\Indexer\NodeIndexer;
use RZ\Roadiz\CoreBundle\SearchEngine\NodeSourceSearchHandlerInterface;
use RZ\Roadiz\CoreBundle\Security\Authorization\Chroot\NodeChrootResolver;
use RZ\Roadiz\CoreBundle\Security\LogTrail;
use RZ\Roadiz\Documents\MediaFinders\RandomImageFinder;
use RZ\Roadiz\Documents\Renderer\RendererInterface;
use RZ\Roadiz\Documents\UrlGenerators\DocumentUrlGeneratorInterface;
Expand Down Expand Up @@ -67,6 +68,7 @@ public static function getSubscribedServices(): array
'em' => EntityManagerInterface::class,
'event_dispatcher' => 'event_dispatcher',
EventDispatcherInterface::class => EventDispatcherInterface::class,
LogTrail::class => LogTrail::class,
'kernel' => KernelInterface::class,
'logger' => LoggerInterface::class,
'nodeApi' => NodeApi::class,
Expand Down Expand Up @@ -313,7 +315,8 @@ protected function getNamespacedView(string $view, string $namespace = ''): stri
* @param mixed $data The initial data for the form
* @param array $options Options for the form
*
* @deprecated Use constructor service injection
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
protected function createNamedFormBuilder(string $name = 'form', mixed $data = null, array $options = []): FormBuilderInterface
{
Expand All @@ -327,6 +330,9 @@ protected function createNamedFormBuilder(string $name = 'form', mixed $data = n
* Creates and returns an EntityListManager instance.
*
* @param class-string<PersistableInterface> $entity Entity class path
*
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function createEntityListManager(string $entity, array $criteria = [], array $ordering = []): EntityListManagerInterface
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,8 @@ abstract class RoadizAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;

public const LOGIN_ROUTE = 'loginPage';

public function __construct(
private readonly UrlGeneratorInterface $urlGenerator,
protected readonly UrlGeneratorInterface $urlGenerator,
private readonly ManagerRegistry $managerRegistry,
private readonly LoggerInterface $logger,
private readonly string $usernamePath = 'username',
Expand Down Expand Up @@ -69,7 +67,7 @@ public function onAuthenticationSuccess(Request $request, TokenInterface $token,
return new RedirectResponse($targetPath);
}

return new RedirectResponse($this->urlGenerator->generate('adminHomePage'));
return new RedirectResponse($this->getDefaultSuccessPath($request));
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
Expand All @@ -84,10 +82,9 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio
return parent::onAuthenticationFailure($request, $exception);
}

protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
abstract protected function getLoginUrl(Request $request): string;

abstract protected function getDefaultSuccessPath(Request $request): string;

/**
* @return array<'username'|'password', string>
Expand Down
70 changes: 70 additions & 0 deletions lib/RoadizCoreBundle/src/Security/LogTrail.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

declare(strict_types=1);

namespace RZ\Roadiz\CoreBundle\Security;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

final readonly class LogTrail
{
public function __construct(private LoggerInterface $logger)
{
}

/**
* Publish a confirmation message in Session flash bag and
* logger interface.
*/
public function publishConfirmMessage(Request $request, string $msg, ?object $source = null): void
{
$this->publishMessage($request, $msg, 'confirm', $source);
}

/**
* Publish an error message in Session flash bag and
* logger interface.
*/
public function publishErrorMessage(Request $request, string $msg, ?object $source = null): void
{
$this->publishMessage($request, $msg, 'error', $source);
}

/**
* Publish a message in Session flash bag and
* logger interface.
*/
protected function publishMessage(
Request $request,
string $msg,
string $level = 'confirm',
?object $source = null,
): void {
$session = $this->getSession($request);
if ($session instanceof Session) {
$session->getFlashBag()->add($level, $msg);
}

switch ($level) {
case 'error':
case 'danger':
case 'fail':
$this->logger->error($msg, ['entity' => $source]);
break;
default:
$this->logger->info($msg, ['entity' => $source]);
break;
}
}

/**
* Returns the current session.
*/
public function getSession(?Request $request): ?SessionInterface
{
return !$request?->hasPreviousSession() ? null : $request->getSession();
}
}
8 changes: 4 additions & 4 deletions lib/RoadizFontBundle/src/Controller/FontFaceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;

final class FontFaceController
final readonly class FontFaceController
{
public function __construct(
private readonly FilesystemOperator $fontStorage,
private readonly ManagerRegistry $managerRegistry,
private readonly Environment $templating,
private FilesystemOperator $fontStorage,
private ManagerRegistry $managerRegistry,
private Environment $templating,
) {
}

Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizRozierBundle/config/routing.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ ajaxSessionMessages:
ping:
path: /rz-admin/ping
methods: [GET]
controller: RZ\Roadiz\RozierBundle\Controller\PingController::indexAction
controller: RZ\Roadiz\RozierBundle\Controller\PingController::pingAction

# CACHES
deleteDoctrineCache:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,19 @@
namespace RZ\Roadiz\RozierBundle\Controller\CustomForm;

use RZ\Roadiz\CoreBundle\Entity\CustomForm;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Themes\Rozier\RozierApp;

final class CustomFormUsageController extends RozierApp
final class CustomFormUsageController extends AbstractController
{
public function usageAction(CustomForm $id): Response
{
$this->denyAccessUnlessGranted('ROLE_ACCESS_CUSTOMFORMS');
$customForm = $id;
$this->assignation['customForm'] = $customForm;
$this->assignation['usages'] = $customForm->getNodes();

return $this->render('@RoadizRozier/custom-forms/usage.html.twig', $this->assignation);
return $this->render('@RoadizRozier/custom-forms/usage.html.twig', [
'customForm' => $customForm,
'usages' => $customForm->getNodes(),
]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@

use Doctrine\Persistence\ManagerRegistry;
use League\Flysystem\FilesystemException;
use Psr\Log\LoggerInterface;
use RZ\Roadiz\CoreBundle\Entity\Document;
use RZ\Roadiz\CoreBundle\Security\LogTrail;
use RZ\Roadiz\Documents\DocumentArchiver;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
Expand All @@ -16,23 +19,20 @@
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Contracts\Translation\TranslatorInterface;
use Themes\Rozier\RozierApp;
use Twig\Error\RuntimeError;

final class DocumentArchiveController extends RozierApp
final class DocumentArchiveController extends AbstractController
{
public function __construct(
private readonly ManagerRegistry $managerRegistry,
private readonly TranslatorInterface $translator,
private readonly DocumentArchiver $documentArchiver,
private readonly LoggerInterface $logger,
private readonly LogTrail $logTrail,
) {
}

/**
* Return an deletion form for multiple docs.
*
* @throws FilesystemException
* @throws RuntimeError
*/
public function bulkDownloadAction(Request $request): Response
{
Expand All @@ -50,39 +50,40 @@ public function bulkDownloadAction(Request $request): Response
'id' => $documentsIds,
]);

if (count($documents) > 0) {
$this->assignation['documents'] = $documents;
$form = $this->buildBulkDownloadForm($documentsIds);
$form->handleRequest($request);
if (0 === count($documents)) {
throw new ResourceNotFoundException();
}

if ($form->isSubmitted() && $form->isValid()) {
try {
return $this->documentArchiver->archiveAndServe($documents, 'Documents archive');
} catch (\Exception $e) {
$this->getLogger()->error($e->getMessage());
$msg = $this->translator->trans('documents.cannot_download');
$this->publishErrorMessage($request, $msg);
}
$assignation = [];
$assignation['documents'] = $documents;
$form = $this->buildBulkDownloadForm($documentsIds);
$form->handleRequest($request);

return $this->redirectToRoute('documentsHomePage');
if ($form->isSubmitted() && $form->isValid()) {
try {
return $this->documentArchiver->archiveAndServe($documents, 'Documents archive');
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
$msg = $this->translator->trans('documents.cannot_download');
$this->logTrail->publishErrorMessage($request, $msg);
}

$this->assignation['form'] = $form->createView();
$this->assignation['action'] = '?'.http_build_query(['documents' => $documentsIds]);
$this->assignation['thumbnailFormat'] = [
'quality' => 50,
'fit' => '128x128',
'sharpen' => 5,
'inline' => false,
'picture' => true,
'controls' => false,
'loading' => 'lazy',
];

return $this->render('@RoadizRozier/documents/bulkDownload.html.twig', $this->assignation);
return $this->redirectToRoute('documentsHomePage');
}

throw new ResourceNotFoundException();
$assignation['form'] = $form->createView();
$assignation['action'] = '?'.http_build_query(['documents' => $documentsIds]);
$assignation['thumbnailFormat'] = [
'quality' => 50,
'fit' => '128x128',
'sharpen' => 5,
'inline' => false,
'picture' => true,
'controls' => false,
'loading' => 'lazy',
];

return $this->render('@RoadizRozier/documents/bulkDownload.html.twig', $assignation);
}

private function buildBulkDownloadForm(array $documentsIds): FormInterface
Expand Down
Loading

0 comments on commit 539806d

Please sign in to comment.