Skip to content

Commit

Permalink
fix: Improved Ajax controllers and fixed setting null newParent as …
Browse files Browse the repository at this point in the history
…`string`
  • Loading branch information
ambroisemaupate committed Jun 21, 2024
1 parent 9bf8c5e commit 07a6df3
Show file tree
Hide file tree
Showing 18 changed files with 125 additions and 162 deletions.
11 changes: 6 additions & 5 deletions lib/Rozier/src/AjaxControllers/AbstractAjaxController.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,15 @@ protected function getTranslation(Request $request): ?TranslationInterface
*/
protected function validateRequest(Request $request, string $method = 'POST', bool $requestCsrfToken = true): bool
{
if ($request->get('_action') == "") {
if (empty($request->get('_action'))) {
throw new BadRequestHttpException('Wrong action requested');
}

if ($requestCsrfToken === true) {
if (!$this->isCsrfTokenValid(static::AJAX_TOKEN_INTENTION, $request->get('_token'))) {
throw new BadRequestHttpException('Bad CSRF token');
}
if (
$requestCsrfToken === true &&
!$this->isCsrfTokenValid(static::AJAX_TOKEN_INTENTION, $request->get('_token'))
) {
throw new BadRequestHttpException('Bad CSRF token');
}

if (
Expand Down
21 changes: 3 additions & 18 deletions lib/Rozier/src/AjaxControllers/AjaxAbstractFieldsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,32 +32,17 @@ protected function findEntity(int|string $entityId): ?AbstractField
*/
protected function handleFieldActions(Request $request, AbstractField $field = null): ?Response
{
/*
* Validate
*/
$this->validateRequest($request);

if ($field !== null) {
$responseArray = null;

/*
* Get the right update method against "_action" parameter
*/
switch ($request->get('_action')) {
case 'updatePosition':
$responseArray = $this->updatePosition($request->request->all(), $field);
break;
if ($request->get('_action') !== 'updatePosition') {
throw new BadRequestHttpException('Action does not exist');
}

if ($responseArray === null) {
$responseArray = [
'statusCode' => '200',
'status' => 'success',
'responseText' => $this->getTranslator()->trans('field.%name%.updated', [
'%name%' => $field->getName(),
]),
];
}
$responseArray = $this->updatePosition($request->request->all(), $field);

return new JsonResponse(
$responseArray,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AjaxCustomFormFieldsController extends AjaxAbstractFieldsController
final class AjaxCustomFormFieldsController extends AjaxAbstractFieldsController
{
/**
* Handle AJAX edition requests for CustomFormFields
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Themes\Rozier\AjaxControllers;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Exception\NotSupported;
use RZ\Roadiz\CoreBundle\Entity\CustomForm;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
Expand All @@ -13,7 +14,7 @@
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Themes\Rozier\Models\CustomFormModel;

class AjaxCustomFormsExplorerController extends AbstractAjaxController
final class AjaxCustomFormsExplorerController extends AbstractAjaxController
{
public function __construct(private readonly UrlGeneratorInterface $urlGenerator)
{
Expand Down Expand Up @@ -63,6 +64,7 @@ public function indexAction(Request $request): Response
*
* @param Request $request
* @return Response
* @throws NotSupported
*/
public function listAction(Request $request): Response
{
Expand Down
18 changes: 8 additions & 10 deletions lib/Rozier/src/AjaxControllers/AjaxDocumentsExplorerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Themes\Rozier\Models\DocumentModel;

class AjaxDocumentsExplorerController extends AbstractAjaxController
final class AjaxDocumentsExplorerController extends AbstractAjaxController
{
public function __construct(
private readonly RendererInterface $renderer,
Expand Down Expand Up @@ -43,11 +43,10 @@ public function indexAction(Request $request): JsonResponse
];

if ($request->query->has('folderId') && $request->get('folderId') > 0) {
$folder = $this->em()
->find(
Folder::class,
$request->get('folderId')
);
$folder = $this->em()->find(
Folder::class,
$request->get('folderId')
);

$arrayFilter['folders'] = [$folder];
}
Expand Down Expand Up @@ -132,14 +131,13 @@ public function listAction(Request $request): JsonResponse
/**
* Normalize response Document list result.
*
* @param array<Document>|\Traversable<Document> $documents
* @param array<Document> $documents
* @return array
*/
private function normalizeDocuments($documents)
private function normalizeDocuments(array $documents): array
{
$documentsArray = [];

/** @var Document $doc */
foreach ($documents as $doc) {
$documentModel = new DocumentModel(
$doc,
Expand All @@ -159,7 +157,7 @@ private function normalizeDocuments($documents)
*
* @return array
*/
private function getTrans()
private function getTrans(): array
{
return [
'editDocument' => $this->getTranslator()->trans('edit.document'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
use Themes\Rozier\Explorer\SettingExplorerItem;
use Themes\Rozier\Explorer\UserExplorerItem;

class AjaxEntitiesExplorerController extends AbstractAjaxController
final class AjaxEntitiesExplorerController extends AbstractAjaxController
{
public function __construct(
private readonly RendererInterface $renderer,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Exception\InvalidParameterException;

class AjaxExplorerProviderController extends AbstractAjaxController
final class AjaxExplorerProviderController extends AbstractAjaxController
{
public function __construct(private readonly ContainerInterface $psrContainer)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use Themes\Rozier\Widgets\FolderTreeWidget;
use Themes\Rozier\Widgets\TreeWidgetFactory;

class AjaxFolderTreeController extends AbstractAjaxController
final class AjaxFolderTreeController extends AbstractAjaxController
{
public function __construct(private readonly TreeWidgetFactory $treeWidgetFactory)
{
Expand Down
53 changes: 17 additions & 36 deletions lib/Rozier/src/AjaxControllers/AjaxFoldersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class AjaxFoldersController extends AbstractAjaxController
final class AjaxFoldersController extends AbstractAjaxController
{
public function __construct(private readonly HandlerFactoryInterface $handlerFactory)
{
Expand All @@ -28,44 +29,25 @@ public function editAction(Request $request, int $folderId): JsonResponse

$folder = $this->em()->find(Folder::class, (int) $folderId);

if ($folder !== null) {
$responseArray = null;

/*
* Get the right update method against "_action" parameter
*/
switch ($request->get('_action')) {
case 'updatePosition':
$this->updatePosition($request->request->all(), $folder);
break;
}

if ($responseArray === null) {
$responseArray = [
'statusCode' => '200',
'status' => 'success',
'responseText' => $this->getTranslator()->trans('folder.%name%.updated', [
'%name%' => $folder->getName(),
])
];
}

return new JsonResponse(
$responseArray,
Response::HTTP_PARTIAL_CONTENT
);
if ($folder === null) {
throw $this->createNotFoundException($this->getTranslator()->trans('folder.does_not_exist'));
}

if ($request->get('_action') !== 'updatePosition') {
throw new BadRequestHttpException('Action does not exist');
}

$responseArray = [
'statusCode' => '403',
'status' => 'danger',
'responseText' => $this->getTranslator()->trans('folder.does_not_exist')
];
$this->updatePosition($request->request->all(), $folder);

return new JsonResponse(
$responseArray,
Response::HTTP_OK
[
'statusCode' => '200',
'status' => 'success',
'responseText' => $this->getTranslator()->trans('folder.%name%.updated', [
'%name%' => $folder->getName(),
])
],
Response::HTTP_PARTIAL_CONTENT
);
}

Expand Down Expand Up @@ -108,10 +90,9 @@ protected function updatePosition(array $parameters, Folder $folder): void
/*
* First, we set the new parent
*/
$parent = null;

if (
!empty($parameters['newParent']) &&
is_numeric($parameters['newParent']) &&
$parameters['newParent'] > 0
) {
/** @var Folder $parent */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
use RZ\Roadiz\CoreBundle\Entity\Folder;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AjaxFoldersExplorerController extends AbstractAjaxController
final class AjaxFoldersExplorerController extends AbstractAjaxController
{
public function indexAction(Request $request): JsonResponse
{
Expand Down
2 changes: 1 addition & 1 deletion lib/Rozier/src/AjaxControllers/AjaxNodeTreeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Themes\Rozier\Widgets\NodeTreeWidget;
use Themes\Rozier\Widgets\TreeWidgetFactory;

class AjaxNodeTreeController extends AbstractAjaxController
final class AjaxNodeTreeController extends AbstractAjaxController
{
public function __construct(
private readonly NodeChrootResolver $nodeChrootResolver,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AjaxNodeTypeFieldsController extends AjaxAbstractFieldsController
final class AjaxNodeTypeFieldsController extends AjaxAbstractFieldsController
{
/**
* Handle AJAX edition requests for NodeTypeFields
Expand Down
2 changes: 1 addition & 1 deletion lib/Rozier/src/AjaxControllers/AjaxNodeTypesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Themes\Rozier\Models\NodeTypeModel;

class AjaxNodeTypesController extends AbstractAjaxController
final class AjaxNodeTypesController extends AbstractAjaxController
{
/**
* @param Request $request
Expand Down
4 changes: 2 additions & 2 deletions lib/Rozier/src/AjaxControllers/AjaxNodesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Workflow\Registry;

class AjaxNodesController extends AbstractAjaxController
final class AjaxNodesController extends AbstractAjaxController
{
public function __construct(
private readonly NodeNamePolicyInterface $nodeNamePolicy,
Expand All @@ -50,7 +50,7 @@ public function getTagsAction(Request $request, int $nodeId): JsonResponse
/** @var Node|null $node */
$node = $this->em()->find(Node::class, (int) $nodeId);
if (null === $node) {
throw new NotFoundHttpException('Node not found');
throw $this->createNotFoundException('Node not found');
}

$this->denyAccessUnlessGranted(NodeVoter::READ, $node);
Expand Down
54 changes: 27 additions & 27 deletions lib/Rozier/src/AjaxControllers/AjaxSearchNodesSourcesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Bundle\SecurityBundle\Security;

class AjaxSearchNodesSourcesController extends AbstractAjaxController
final class AjaxSearchNodesSourcesController extends AbstractAjaxController
{
public const RESULT_COUNT = 10;

Expand Down Expand Up @@ -48,42 +48,42 @@ public function searchAction(Request $request): Response
/** @var array $nodesSources */
$nodesSources = $searchHandler->getNodeSourcesBySearchTerm(
$request->get('searchTerms'),
static::RESULT_COUNT
self::RESULT_COUNT
);

if (count($nodesSources) > 0) {
$responseArray = [
if (count($nodesSources) === 0) {
return new JsonResponse([
'statusCode' => Response::HTTP_OK,
'status' => 'success',
'data' => [],
'responseText' => count($nodesSources) . ' results found.',
];

foreach ($nodesSources as $source) {
if (
$source instanceof NodesSources &&
$this->security->isGranted(NodeVoter::READ, $source) &&
!key_exists($source->getNode()->getId(), $responseArray['data'])
) {
$responseArray['data'][$source->getNode()->getId()] = $this->getNodeSourceData($source);
}
}
/*
* Only display one nodeSource
*/
$responseArray['data'] = array_values($responseArray['data']);

return new JsonResponse(
$responseArray
);
'responseText' => 'No results found.',
]);
}

return new JsonResponse([
$responseArray = [
'statusCode' => Response::HTTP_OK,
'status' => 'success',
'data' => [],
'responseText' => 'No results found.',
]);
'responseText' => count($nodesSources) . ' results found.',
];

foreach ($nodesSources as $source) {
if (
$source instanceof NodesSources &&
$this->security->isGranted(NodeVoter::READ, $source) &&
!key_exists($source->getNode()->getId(), $responseArray['data'])
) {
$responseArray['data'][$source->getNode()->getId()] = $this->getNodeSourceData($source);
}
}
/*
* Only display one nodeSource
*/
$responseArray['data'] = array_values($responseArray['data']);

return new JsonResponse(
$responseArray
);
}

protected function getNodeSourceData(NodesSources $source): array
Expand Down
2 changes: 1 addition & 1 deletion lib/Rozier/src/AjaxControllers/AjaxSessionMessages.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;

class AjaxSessionMessages extends AbstractAjaxController
final class AjaxSessionMessages extends AbstractAjaxController
{
public function getMessagesAction(Request $request): JsonResponse
{
Expand Down
Loading

0 comments on commit 07a6df3

Please sign in to comment.