apply more cs rules for php-cs

This commit is contained in:
2023-10-17 13:27:03 +02:00
parent 0b0cbed9db
commit bc2041cbdd
1485 changed files with 8169 additions and 9620 deletions

View File

@@ -24,8 +24,6 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use function trim;
final class AddressReferenceAPIController extends ApiController
{
public function __construct(private readonly AddressReferenceRepository $addressReferenceRepository, private readonly PaginatorFactory $paginatorFactory) {}
@@ -43,7 +41,7 @@ final class AddressReferenceAPIController extends ApiController
$pattern = $request->query->get('q');
if ('' === trim((string) $pattern)) {
if ('' === \trim((string) $pattern)) {
throw new BadRequestHttpException('the search pattern is empty');
}

View File

@@ -72,22 +72,22 @@ class DefaultController extends AbstractController
],
[
'name' => 'Link 2',
//'link' => "http://localhost",
// 'link' => "http://localhost",
'content' => 'Dui sapien eget mi proin sed libero. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Turpis nunc eget lorem dolor. Phasellus egestas tellus rutrum tellus. Diam sit amet nisl suscipit adipiscing bibendum est ultricies integer. Duis ultricies lacus sed turpis tincidunt id. Nisl suscipit adipiscing bibendum est ultricies integer. Elementum nibh tellus molestie nunc non blandit massa enim. Faucibus in ornare quam viverra orci sagittis eu. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Accumsan sit amet nulla facilisi morbi. Leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim. Amet est placerat in egestas erat imperdiet sed euismod. Quis auctor elit sed vulputate mi. Mauris nunc congue nisi vitae suscipit tellus mauris a diam. At volutpat diam ut venenatis. Facilisis gravida neque convallis a cras semper.',
],
[
'name' => 'Link 3',
//'link' => "http://localhost",
// 'link' => "http://localhost",
'content' => 'In ornare quam viverra orci sagittis eu volutpat. Ac tincidunt vitae semper quis lectus nulla at volutpat. Placerat duis ultricies lacus sed turpis tincidunt. Augue interdum velit euismod in pellentesque. Felis eget nunc lobortis mattis aliquam. Volutpat lacus laoreet non curabitur gravida arcu. Gravida cum sociis natoque penatibus et magnis dis parturient montes. Nisl pretium fusce id velit ut tortor. Nunc scelerisque viverra mauris in aliquam sem fringilla ut. Magna eget est lorem ipsum dolor sit. Non consectetur a erat nam at lectus urna. Eget est lorem ipsum dolor sit amet consectetur adipiscing elit. Sed velit dignissim sodales ut.',
],
[
'name' => 'Link 4',
'link' => 'http://localhost',
//'content' => "Ut tellus elementum sagittis vitae et. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra. Hendrerit gravida rutrum quisque non tellus orci ac auctor augue. Eleifend quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Dictumst quisque sagittis purus sit. Suspendisse sed nisi lacus sed viverra. Pretium quam vulputate dignissim suspendisse in est ante. Id eu nisl nunc mi ipsum. Ut venenatis tellus in metus vulputate. Ut morbi tincidunt augue interdum velit euismod.",
// 'content' => "Ut tellus elementum sagittis vitae et. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra. Hendrerit gravida rutrum quisque non tellus orci ac auctor augue. Eleifend quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Dictumst quisque sagittis purus sit. Suspendisse sed nisi lacus sed viverra. Pretium quam vulputate dignissim suspendisse in est ante. Id eu nisl nunc mi ipsum. Ut venenatis tellus in metus vulputate. Ut morbi tincidunt augue interdum velit euismod.",
],
[
'name' => 'Link 5',
//'link' => "http://localhost",
// 'link' => "http://localhost",
'content' => 'Vel elit scelerisque mauris pellentesque pulvinar. Ornare suspendisse sed nisi lacus sed viverra tellus. Massa tincidunt dui ut ornare lectus sit. Congue nisi vitae suscipit tellus mauris a diam. At auctor urna nunc id cursus metus aliquam. Viverra accumsan in nisl nisi scelerisque eu ultrices vitae. Mattis aliquam faucibus purus in massa tempor nec feugiat. Et leo duis ut diam quam. Auctor augue mauris augue neque. Purus ut faucibus pulvinar elementum integer enim neque volutpat. Scelerisque felis imperdiet proin fermentum leo. Diam sit amet nisl suscipit adipiscing bibendum est ultricies. Consectetur libero id faucibus nisl tincidunt. Vel fringilla est ullamcorper eget nulla facilisi. Pharetra diam sit amet nisl suscipit adipiscing. Dignissim diam quis enim lobortis. Auctor eu augue ut lectus arcu bibendum at varius.',
],
],

View File

@@ -25,9 +25,7 @@ use Chill\MainBundle\Redis\ChillRedis;
use Chill\MainBundle\Repository\SavedExportRepositoryInterface;
use Chill\MainBundle\Security\Authorization\SavedExportVoter;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Psr\Log\LoggerInterface;
use RedisException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@@ -39,12 +37,8 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
use function serialize;
use function unserialize;
/**
* Class ExportController
@@ -109,6 +103,7 @@ class ExportController extends AbstractController
* @param string $alias
*
* @return \Symfony\Component\HttpFoundation\Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/exports/generate/{alias}", name="chill_main_export_generate", methods={"GET"})
*/
public function generateAction(Request $request, $alias)
@@ -131,7 +126,7 @@ class ExportController extends AbstractController
/**
* @Route("/{_locale}/exports/generate-from-saved/{id}", name="chill_main_export_generate_from_saved")
*
* @throws RedisException
* @throws \RedisException
*/
public function generateFromSavedExport(SavedExport $savedExport): RedirectResponse
{
@@ -139,7 +134,7 @@ class ExportController extends AbstractController
$key = md5(uniqid((string) random_int(0, mt_getrandmax()), false));
$this->redis->setEx($key, 3600, serialize($savedExport->getOptions()));
$this->redis->setEx($key, 3600, \serialize($savedExport->getOptions()));
return $this->redirectToRoute(
'chill_main_export_download',
@@ -153,6 +148,7 @@ class ExportController extends AbstractController
/**
* Render the list of available exports.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/exports/", name="chill_main_export_index")
*/
public function indexAction(): Response
@@ -186,7 +182,7 @@ class ExportController extends AbstractController
$exportManager = $this->exportManager;
$export = $exportManager->getExport($alias);
if ($exportManager->isGrantedForElement($export) === false) {
if (false === $exportManager->isGrantedForElement($export)) {
throw $this->createAccessDeniedException('The user does not have access to this export');
}
@@ -279,7 +275,7 @@ class ExportController extends AbstractController
$options = match ($step) {
'export', 'generate_export' => [
'export_alias' => $alias,
'picked_centers' => $exportManager->getPickedCenters($data['centers'])
'picked_centers' => $exportManager->getPickedCenters($data['centers']),
],
'formatter', 'generate_formatter' => [
'export_alias' => $alias,
@@ -332,7 +328,7 @@ class ExportController extends AbstractController
* When the method is POST, the form is stored if valid, and a redirection
* is done to next step.
*/
private function exportFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, ?SavedExport $savedExport = null): Response
private function exportFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, SavedExport $savedExport = null): Response
{
$exportManager = $this->exportManager;
@@ -350,7 +346,7 @@ class ExportController extends AbstractController
$form = $this->createCreateFormExport($alias, 'export', $data, $savedExport);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -365,11 +361,11 @@ class ExportController extends AbstractController
);
$this->session->set('export_step', $data);
//redirect to next step
// redirect to next step
return $this->redirectToRoute('chill_main_export_new', [
'step' => $this->getNextStep('export', $export),
'alias' => $alias,
'from_saved' => $request->get('from_saved', '')
'from_saved' => $request->get('from_saved', ''),
]);
}
$this->logger->debug('form export is invalid', [
@@ -390,7 +386,7 @@ class ExportController extends AbstractController
* If the form is posted and valid, store the data in session and
* redirect to the next step.
*/
private function formatterFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, ?SavedExport $savedExport = null): Response
private function formatterFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, SavedExport $savedExport = null): Response
{
// check we have data from the previous step (export step)
$data = $this->session->get('export_step', null);
@@ -404,7 +400,7 @@ class ExportController extends AbstractController
$form = $this->createCreateFormExport($alias, 'formatter', $data, $savedExport);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -415,7 +411,7 @@ class ExportController extends AbstractController
$request->request->all()
);
//redirect to next step
// redirect to next step
return $this->redirectToRoute('chill_main_export_new', [
'alias' => $alias,
'step' => $this->getNextStep('formatter', $export),
@@ -440,12 +436,11 @@ class ExportController extends AbstractController
*
* The data from previous steps is removed from session.
*
* @param \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export
* @param string $alias
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
private function forwardToGenerate(Request $request, \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export, $alias, ?SavedExport $savedExport)
private function forwardToGenerate(Request $request, DirectExportInterface|ExportInterface $export, $alias, ?SavedExport $savedExport)
{
$dataCenters = $this->session->get('centers_step_raw', null);
$dataFormatter = $this->session->get('formatter_step_raw', null);
@@ -468,7 +463,7 @@ class ExportController extends AbstractController
unset($parameters['_token']);
$key = md5(uniqid((string) random_int(0, mt_getrandmax()), false));
$this->redis->setEx($key, 3600, serialize($parameters));
$this->redis->setEx($key, 3600, \serialize($parameters));
// remove data from session
$this->session->remove('export_step_raw');
@@ -497,7 +492,7 @@ class ExportController extends AbstractController
$formExport->submit($rawData['export']);
$dataExport = $formExport->getData();
if (count($rawData['formatter']) > 0) {
if (\count($rawData['formatter']) > 0) {
$formFormatter = $this->createCreateFormExport(
$alias,
'generate_formatter',
@@ -513,16 +508,17 @@ class ExportController extends AbstractController
/**
* @param string $alias
*
* @return Response
*/
private function selectCentersStep(Request $request, \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export, $alias, ?SavedExport $savedExport = null)
private function selectCentersStep(Request $request, DirectExportInterface|ExportInterface $export, $alias, SavedExport $savedExport = null)
{
/** @var \Chill\MainBundle\Export\ExportManager $exportManager */
$exportManager = $this->exportManager;
$form = $this->createCreateFormExport($alias, 'centers', [], $savedExport);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -533,14 +529,13 @@ class ExportController extends AbstractController
// check ACL
if (
$exportManager->isGrantedForElement(
false === $exportManager->isGrantedForElement(
$export,
null,
$exportManager->getPickedCenters($data['centers'])
) === false
)
) {
throw $this->createAccessDeniedException('you do not have '
. 'access to this export for those centers');
throw $this->createAccessDeniedException('you do not have access to this export for those centers');
}
$this->session->set(
@@ -589,20 +584,19 @@ class ExportController extends AbstractController
*
* This method provides a centralized way of handling next/previous step.
*
* @param string $step the current step
* @param \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export
* @param bool $reverse set to true to get the previous step
*
* @throws LogicException if there is no step before or after the given step
* @param string $step the current step
* @param bool $reverse set to true to get the previous step
*
* @return string the next/current step
*
* @throws \LogicException if there is no step before or after the given step
*/
private function getNextStep($step, \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export, $reverse = false)
private function getNextStep($step, DirectExportInterface|ExportInterface $export, $reverse = false)
{
switch ($step) {
case 'centers':
if (false !== $reverse) {
throw new LogicException("there is no step before 'export'");
throw new \LogicException("there is no step before 'export'");
}
return 'export';
@@ -622,13 +616,13 @@ class ExportController extends AbstractController
case 'generate':
if (false === $reverse) {
throw new LogicException("there is no step after 'generate'");
throw new \LogicException("there is no step after 'generate'");
}
return 'formatter';
default:
throw new LogicException("the step {$step} is not defined.");
throw new \LogicException("the step {$step} is not defined.");
}
}
@@ -638,7 +632,7 @@ class ExportController extends AbstractController
throw $this->createNotFoundException('key does not exists');
}
if ($this->redis->exists($key) !== 1) {
if (1 !== $this->redis->exists($key)) {
$this->addFlash('error', $this->translator->trans('This report is not available any more'));
throw $this->createNotFoundException('key does not exists');
@@ -647,10 +641,10 @@ class ExportController extends AbstractController
$serialized = $this->redis->get($key);
if (false === $serialized) {
throw new LogicException('the key could not be reached from redis');
throw new \LogicException('the key could not be reached from redis');
}
$rawData = unserialize($serialized);
$rawData = \unserialize($serialized);
$this->logger->notice('[export] choices for an export unserialized', [
'key' => $key,
@@ -668,7 +662,7 @@ class ExportController extends AbstractController
};
if (null !== $savedExport && !$this->security->isGranted(SavedExportVoter::EDIT, $savedExport)) {
throw new AccessDeniedHttpException("saved export edition not allowed");
throw new AccessDeniedHttpException('saved export edition not allowed');
}
return $savedExport;

View File

@@ -36,7 +36,6 @@ class LocationApiController extends ApiController
/**
* @param QueryBuilder $query
* @param mixed $_format
*/
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
{

View File

@@ -35,6 +35,7 @@ class LoginController extends AbstractController
* Show a login form.
*
* @return Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/login", name="login")
*/
public function loginAction(Request $request)

View File

@@ -19,14 +19,12 @@ use Chill\MainBundle\Security\Authorization\NotificationVoter;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\MainBundle\Serializer\Model\Counter;
use Doctrine\ORM\EntityManagerInterface;
use RuntimeException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\SerializerInterface;
use UnexpectedValueException;
/**
* @Route("/api/1.0/main/notification")
@@ -91,13 +89,13 @@ class NotificationApiController
$user = $this->security->getUser();
if (!$user instanceof User) {
throw new RuntimeException('not possible to mark as read by this user');
throw new \RuntimeException('not possible to mark as read by this user');
}
match ($target) {
'read' => $notification->markAsReadBy($user),
'unread' => $notification->markAsUnreadBy($user),
default => throw new UnexpectedValueException("target not supported: {$target}"),
default => throw new \UnexpectedValueException("target not supported: {$target}"),
};
$this->entityManager->flush();

View File

@@ -148,7 +148,7 @@ class NotificationController extends AbstractController
throw new AccessDeniedHttpException('You must be authenticated and a user to create a notification');
}
foreach (['accessKey'/*, 'email'*/] as $param) {
foreach (['accessKey'/* , 'email' */] as $param) {
if (!$request->query->has($param)) {
throw new BadRequestHttpException("Missing {$param} parameter");
}
@@ -191,7 +191,7 @@ class NotificationController extends AbstractController
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');
$currentUser = $this->security->getUser();
$notificationsNbr = $this->notificationRepository->countAllForAttendee(($currentUser));
$notificationsNbr = $this->notificationRepository->countAllForAttendee($currentUser);
$paginator = $this->paginatorFactory->create($notificationsNbr);
$notifications = $this->notificationRepository->findAllForAttendee(
@@ -264,7 +264,7 @@ class NotificationController extends AbstractController
return $this->redirectToRoute('chill_main_notification_show', [
'id' => $notification->getId(),
'_fragment' => 'comment-' . $commentId,
'_fragment' => 'comment-'.$commentId,
]);
}

View File

@@ -17,8 +17,6 @@ use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverEvent;
use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverVoter;
use Chill\MainBundle\Security\PasswordRecover\RecoverPasswordHelper;
use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use DateInterval;
use DateTimeImmutable;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
@@ -88,6 +86,7 @@ class PasswordController extends AbstractController
/**
* @return Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/request-changed", name="password_request_recover_changed")
*/
public function changeConfirmedAction()
@@ -96,15 +95,14 @@ class PasswordController extends AbstractController
}
/**
* @return Response|\Symfony\Component\HttpFoundation\RedirectResponse
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/recover", name="password_recover")
*/
public function recoverAction(Request $request): \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
public function recoverAction(Request $request): Response|\Symfony\Component\HttpFoundation\RedirectResponse
{
if (false === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return new Response($this->translator->trans('You are not allowed '
. 'to try to recover password, due to mitigating possible '
. 'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
.'to try to recover password, due to mitigating possible '
.'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
}
$query = $request->query;
@@ -165,15 +163,14 @@ class PasswordController extends AbstractController
* @throws \Doctrine\ORM\NoResultException
* @throws \Doctrine\ORM\NonUniqueResultException
*
* @return Response|\Symfony\Component\HttpFoundation\RedirectResponse
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/request-recover", name="password_request_recover")
*/
public function requestRecoverAction(Request $request): \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
public function requestRecoverAction(Request $request): Response|\Symfony\Component\HttpFoundation\RedirectResponse
{
if (false === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return new Response($this->translator->trans('You are not allowed '
. 'to try to recover password, due to mitigating possible '
. 'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
.'to try to recover password, due to mitigating possible '
.'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
}
$form = $this->requestRecoverForm();
@@ -194,17 +191,17 @@ class PasswordController extends AbstractController
if (empty($user->getEmail())) {
$this->addFlash('error', $this->translator->trans('This account does not have an email address. '
. 'Please ask your administrator to renew your password.'));
.'Please ask your administrator to renew your password.'));
} else {
if (false === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN, $user)) {
return new Response($this->translator->trans('You are not allowed '
. 'to try to recover password, due to mitigating possible '
. 'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
.'to try to recover password, due to mitigating possible '
.'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
}
$this->recoverPasswordHelper->sendRecoverEmail(
$user,
(new DateTimeImmutable('now'))->add(new DateInterval('PT30M'))
(new \DateTimeImmutable('now'))->add(new \DateInterval('PT30M'))
);
// logging for prod
@@ -238,6 +235,7 @@ class PasswordController extends AbstractController
/**
* @return Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/request-confirm", name="password_request_recover_confirm")
*/
public function requestRecoverConfirmAction()
@@ -247,6 +245,7 @@ class PasswordController extends AbstractController
/**
* @return Response
*
* @Route("/{_locale}/my/password", name="change_my_password")
*/
public function UserPasswordAction(Request $request)
@@ -310,7 +309,7 @@ class PasswordController extends AbstractController
->orWhere($qb->expr()->eq('u.emailCanonical', 'UNACCENT(LOWER(:pattern))'))
->setParameter('pattern', $pattern);
if ((int) $qb->getQuery()->getSingleScalarResult() !== 1) {
if (1 !== (int) $qb->getQuery()->getSingleScalarResult()) {
$context->addViolation('This username or email does not exists');
}
},

View File

@@ -19,9 +19,6 @@ use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use function array_key_exists;
use function json_decode;
class PermissionApiController extends AbstractController
{
public function __construct(private readonly DenormalizerInterface $denormalizer, private readonly Security $security) {}
@@ -35,21 +32,17 @@ class PermissionApiController extends AbstractController
{
$this->denyAccessUnlessGranted('ROLE_USER');
$data = json_decode($request->getContent(), true);
$data = \json_decode($request->getContent(), true);
if (null === $data) {
throw new BadRequestHttpException(sprintf(
'Could not decode json received, or data invalid: %s, %s',
json_last_error(),
json_last_error_msg()
));
throw new BadRequestHttpException(sprintf('Could not decode json received, or data invalid: %s, %s', json_last_error(), json_last_error_msg()));
}
if (!array_key_exists('object', $data)) {
if (!\array_key_exists('object', $data)) {
throw new BadRequestHttpException('the object key is not present');
}
if (!array_key_exists('class', $data)) {
if (!\array_key_exists('class', $data)) {
throw new BadRequestHttpException('the class key is not present');
}

View File

@@ -21,7 +21,6 @@ use Chill\MainBundle\Repository\RoleScopeRepository;
use Chill\MainBundle\Security\RoleProvider;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityManagerInterface;
use RuntimeException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormInterface;
@@ -31,8 +30,6 @@ use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
/**
* Class PermissionsGroupController.
*/
@@ -75,7 +72,7 @@ final class PermissionsGroupController extends AbstractController
$permissionsGroup->addRoleScope($roleScope);
$violations = $this->validator->validate($permissionsGroup);
if ($violations->count() === 0) {
if (0 === $violations->count()) {
$this->em->flush();
$this->addFlash(
@@ -132,6 +129,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Creates a new PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/create", name="admin_permissionsgroup_create", methods={"POST"})
*/
public function createAction(Request $request): Response
@@ -155,6 +153,7 @@ final class PermissionsGroupController extends AbstractController
/**
* remove an association between permissionsGroup and roleScope.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{pgid}/delete_link_role_scope/{rsid}", name="admin_permissionsgroup_delete_role_scope", methods={"DELETE"})
*/
public function deleteLinkRoleScopeAction(int $pgid, int $rsid): Response
@@ -172,11 +171,11 @@ final class PermissionsGroupController extends AbstractController
try {
$permissionsGroup->removeRoleScope($roleScope);
} catch (RuntimeException) {
} catch (\RuntimeException) {
$this->addFlash(
'notice',
$this->translator->trans("The role '%role%' and circle "
. "'%scope%' is not associated with this permission group", [
."'%scope%' is not associated with this permission group", [
'%role%' => $this->translator->trans($roleScope->getRole()),
'%scope%' => $this->translatableStringHelper
->localize($roleScope->getScope()->getName()),
@@ -188,11 +187,11 @@ final class PermissionsGroupController extends AbstractController
$this->em->flush();
if ($roleScope->getScope() !== null) {
if (null !== $roleScope->getScope()) {
$this->addFlash(
'notice',
$this->translator->trans("The role '%role%' on circle "
. "'%scope%' has been removed", [
."'%scope%' has been removed", [
'%role%' => $this->translator->trans($roleScope->getRole()),
'%scope%' => $this->translatableStringHelper
->localize($roleScope->getScope()->getName()),
@@ -212,6 +211,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Displays a form to edit an existing PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{id}/edit", name="admin_permissionsgroup_edit")
*/
public function editAction(int $id): Response
@@ -259,6 +259,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Lists all PermissionsGroup entities.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/", name="admin_permissionsgroup")
*/
public function indexAction(): Response
@@ -272,6 +273,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Displays a form to create a new PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/new", name="admin_permissionsgroup_new")
*/
public function newAction(): Response
@@ -287,6 +289,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Finds and displays a PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{id}/show", name="admin_permissionsgroup_show")
*/
public function showAction(int $id): Response
@@ -304,11 +307,11 @@ final class PermissionsGroupController extends AbstractController
usort(
$roleScopes,
static function (RoleScope $a, RoleScope $b) use ($translatableStringHelper) {
if ($a->getScope() === null) {
if (null === $a->getScope()) {
return 1;
}
if ($b->getScope() === null) {
if (null === $b->getScope()) {
return +1;
}
@@ -339,6 +342,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Edits an existing PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{id}/update", name="admin_permissionsgroup_update", methods={"POST", "PUT"})
*/
public function updateAction(Request $request, int $id): Response
@@ -347,8 +351,7 @@ final class PermissionsGroupController extends AbstractController
->find($id);
if (!$permissionsGroup) {
throw $this->createNotFoundException('Unable to find Permissions'
. 'Group entity.');
throw $this->createNotFoundException('Unable to find PermissionsGroup entity.');
}
$editForm = $this->createEditForm($permissionsGroup);
@@ -396,7 +399,7 @@ final class PermissionsGroupController extends AbstractController
* get a role scope by his parameters. The role scope is persisted if it
* doesn't exist in database.
*/
protected function getPersistentRoleScopeBy(string $role, ?Scope $scope = null): RoleScope
protected function getPersistentRoleScopeBy(string $role, Scope $scope = null): RoleScope
{
$roleScope = $this->roleScopeRepository
->findOneBy(['role' => $role, 'scope' => $scope]);
@@ -487,7 +490,7 @@ final class PermissionsGroupController extends AbstractController
$expandedRoles = [];
foreach ($roleScopes as $roleScope) {
if (!array_key_exists($roleScope->getRole(), $expandedRoles)) {
if (!\array_key_exists($roleScope->getRole(), $expandedRoles)) {
$expandedRoles[$roleScope->getRole()] =
array_map(
static fn ($role) => $role,

View File

@@ -19,8 +19,6 @@ use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use function array_map;
/**
* Class PostalCodeController.
*/
@@ -55,21 +53,21 @@ class PostalCodeController extends AbstractController
->createQuery(
sprintf(
'SELECT p.id AS id, p.name AS name, p.code AS code, '
. 'country.name AS country_name, '
. 'country.countryCode AS country_code '
. 'FROM %s p '
. 'JOIN p.country country '
. 'WHERE LOWER(p.name) LIKE LOWER(:pattern) OR LOWER(p.code) LIKE LOWER(:pattern) '
. 'ORDER BY code',
.'country.name AS country_name, '
.'country.countryCode AS country_code '
.'FROM %s p '
.'JOIN p.country country '
.'WHERE LOWER(p.name) LIKE LOWER(:pattern) OR LOWER(p.code) LIKE LOWER(:pattern) '
.'ORDER BY code',
PostalCode::class
)
)
->setParameter('pattern', '%' . $pattern . '%')
->setParameter('pattern', '%'.$pattern.'%')
->setMaxResults(30);
$results = array_map(function ($row) {
$results = \array_map(function ($row) {
$row['country_name'] = $this->translatableStringHelper->localize($row['country_name']);
$row['text'] = $row['code'] . ' ' . $row['name'] . ' (' . $row['country_name'] . ')';
$row['text'] = $row['code'].' '.$row['name'].' ('.$row['country_name'].')';
return $row;
}, $query->getResult(Query::HYDRATE_ARRAY));

View File

@@ -30,9 +30,7 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
class SavedExportController
{
@@ -139,7 +137,7 @@ class SavedExportController
'@ChillMain/SavedExport/index.html.twig',
[
'grouped_exports' => $exportsGrouped,
'total' => count($exports),
'total' => \count($exports),
]
)
);

View File

@@ -24,6 +24,7 @@ class ScopeController extends AbstractController
{
/**
* Creates a new Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/create", name="admin_scope_create", methods={"POST"})
*/
public function createAction(Request $request)
@@ -48,6 +49,7 @@ class ScopeController extends AbstractController
/**
* Displays a form to edit an existing Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/{id}/edit", name="admin_scope_edit")
*/
public function editAction(mixed $id)
@@ -70,6 +72,7 @@ class ScopeController extends AbstractController
/**
* Lists all Scope entities.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/", name="admin_scope")
*/
public function indexAction()
@@ -85,6 +88,7 @@ class ScopeController extends AbstractController
/**
* Displays a form to create a new Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/new", name="admin_scope_new")
*/
public function newAction()
@@ -118,6 +122,7 @@ class ScopeController extends AbstractController
/**
* Edits an existing Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/{id}/update", name="admin_scope_update", methods={"POST", "PUT"})
*/
public function updateAction(Request $request, mixed $id)

View File

@@ -27,10 +27,6 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
use function key;
use function reset;
/**
* Class SearchController.
*/
@@ -50,8 +46,7 @@ class SearchController extends AbstractController
$search = $this->searchProvider
->getHasAdvancedFormByName($name);
} catch (\Chill\MainBundle\Search\UnknowSearchNameException) {
throw $this->createNotFoundException('no advanced search for '
. "{$name}");
throw $this->createNotFoundException('no advanced search for '."{$name}");
}
if ($request->query->has('q')) {
@@ -96,7 +91,7 @@ class SearchController extends AbstractController
$advancedSearchProviders = $searchProvider
->getHasAdvancedFormSearchServices();
if (count($advancedSearchProviders) === 1) {
if (1 === \count($advancedSearchProviders)) {
return $this->redirectToRoute('chill_main_advanced_search', [
'name' => array_key_first($advancedSearchProviders),
]);
@@ -119,7 +114,7 @@ class SearchController extends AbstractController
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('Your search is empty. '
. 'Please provide search terms.'),
.'Please provide search terms.'),
'pattern' => $pattern,
]
);
@@ -138,7 +133,7 @@ class SearchController extends AbstractController
if (null === $name) {
if ('json' === $_format) {
return new JsonResponse('Currently, we still do not aggregate results '
. 'from different providers', JsonResponse::HTTP_BAD_REQUEST);
.'from different providers', JsonResponse::HTTP_BAD_REQUEST);
}
// no specific search selected. Rendering result in "preview" mode
@@ -166,7 +161,7 @@ class SearchController extends AbstractController
), ];
if ('json' === $_format) {
return new JsonResponse(reset($results));
return new JsonResponse(\reset($results));
}
}
} catch (UnknowSearchDomainException $ex) {
@@ -174,18 +169,18 @@ class SearchController extends AbstractController
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('The domain %domain% '
. 'is unknow. Please check your search.', ['%domain%' => $ex->getDomain()]),
.'is unknow. Please check your search.', ['%domain%' => $ex->getDomain()]),
'pattern' => $pattern,
]
);
} catch (UnknowSearchNameException $ex) {
throw $this->createNotFoundException('The name ' . $ex->getName() . ' is not found');
throw $this->createNotFoundException('The name '.$ex->getName().' is not found');
} catch (ParsingException $ex) {
return $this->render(
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('Invalid terms') .
': ' . $this->translator->trans($ex->getMessage()),
'message' => $this->translator->trans('Invalid terms').
': '.$this->translator->trans($ex->getMessage()),
'pattern' => $pattern,
]
);
@@ -202,13 +197,12 @@ class SearchController extends AbstractController
*/
public function searchApi(Request $request, mixed $_format): JsonResponse
{
//TODO this is an incomplete implementation
// TODO this is an incomplete implementation
$query = $request->query->get('q', '');
$types = $request->query->get('type', []);
if (count($types) === 0) {
throw new BadRequestHttpException('The request must contains at '
. ' one type');
if (0 === \count($types)) {
throw new BadRequestHttpException('The request must contains at one type');
}
try {

View File

@@ -18,8 +18,6 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use function count;
class TimelineCenterController extends AbstractController
{
public function __construct(protected TimelineBuilder $timelineBuilder, protected PaginatorFactory $paginatorFactory, private readonly Security $security) {}
@@ -40,7 +38,7 @@ class TimelineCenterController extends AbstractController
$centers[] = $group->getCenter();
}
if (0 === count($centers)) {
if (0 === \count($centers)) {
throw $this->createNotFoundException();
}

View File

@@ -68,10 +68,6 @@ class UserApiController extends ApiController
}
}
/**
* @param mixed $query
* @param mixed $_format
*/
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
{
return $query->orderBy('e.label', 'ASC');

View File

@@ -22,7 +22,6 @@ use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Repository\UserRepository;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Form;
@@ -63,11 +62,11 @@ class UserController extends CRUDController
);
$user->addGroupCenter($groupCenter);
if ($this->validator->validate($user)->count() === 0) {
if (0 === $this->validator->validate($user)->count()) {
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('The '
. 'permissions have been successfully added to the user'));
.'permissions have been successfully added to the user'));
$returnPathParams = $request->query->has('returnPath') ?
['returnPath' => $request->query->get('returnPath')] : [];
@@ -115,7 +114,7 @@ class UserController extends CRUDController
try {
$user->removeGroupCenter($groupCenter);
} catch (RuntimeException $ex) {
} catch (\RuntimeException $ex) {
$this->addFlash('error', $this->get('translator')->trans($ex->getMessage()));
return $this->redirectToRoute('chill_crud_admin_user_edit', ['id' => $uid]);
@@ -135,13 +134,7 @@ class UserController extends CRUDController
$entity = $this->getEntity($action, $id, $request);
if (null === $entity) {
throw $this->createNotFoundException(
sprintf(
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
throw $this->createNotFoundException(sprintf('The %s with id %s is not found', $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $entity);
@@ -176,7 +169,7 @@ class UserController extends CRUDController
return $result;
}
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_index');
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_index');
}
if ($form->isSubmitted()) {
@@ -272,7 +265,7 @@ class UserController extends CRUDController
->build();
}
protected function countEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null): int
protected function countEntities(string $action, Request $request, FilterOrderHelper $filterOrder = null): int
{
if (!$filterOrder instanceof FilterOrderHelper) {
return parent::countEntities($action, $request, $filterOrder);
@@ -285,7 +278,7 @@ class UserController extends CRUDController
return $this->userRepository->countByUsernameOrEmail($filterOrder->getQueryString());
}
protected function createFormFor(string $action, $entity, ?string $formClass = null, array $formOptions = []): FormInterface
protected function createFormFor(string $action, $entity, string $formClass = null, array $formOptions = []): FormInterface
{
// for "new", add special config
if ('new' === $action) {
@@ -329,7 +322,7 @@ class UserController extends CRUDController
Request $request,
int $totalItems,
PaginatorInterface $paginator,
?FilterOrderHelper $filterOrder = null
FilterOrderHelper $filterOrder = null
) {
if (0 === $totalItems) {
return [];

View File

@@ -47,7 +47,7 @@ final readonly class UserExportController
$csv = Writer::createFromPath('php://temp', 'r+');
$csv->insertOne(
array_map(
fn (string $e) => $this->translator->trans('admin.users.export.' . $e),
fn (string $e) => $this->translator->trans('admin.users.export.'.$e),
[
'id',
// 'username',
@@ -57,7 +57,7 @@ final readonly class UserExportController
'civility_abbreviation',
'civility_name',
'label',
'mainCenter_id' ,
'mainCenter_id',
'mainCenter_name',
'mainScope_id',
'mainScope_name',
@@ -67,7 +67,7 @@ final readonly class UserExportController
'currentLocation_name',
'mainLocation_id',
'mainLocation_name',
'absenceStart'
'absenceStart',
]
)
);
@@ -94,6 +94,7 @@ final readonly class UserExportController
* @throws \League\Csv\CannotInsertRecord
* @throws \League\Csv\Exception
* @throws \League\Csv\UnavailableStream
*
* @Route("/{_locale}/admin/main/users/export/permissions.{_format}", requirements={"_format": "csv"}, name="chill_main_users_export_permissions")
*/
public function userPermissionsList(string $_format = 'csv'): StreamedResponse
@@ -107,7 +108,7 @@ final readonly class UserExportController
$csv = Writer::createFromPath('php://temp', 'r+');
$csv->insertOne(
array_map(
fn (string $e) => $this->translator->trans('admin.users.export.' . $e),
fn (string $e) => $this->translator->trans('admin.users.export.'.$e),
[
'id',
'username',

View File

@@ -18,7 +18,6 @@ use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\MainBundle\Serializer\Model\Counter;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@@ -142,12 +141,12 @@ class WorkflowApiController
'final' => match ($action) {
'subscribe' => $entityWorkflow->addSubscriberToFinal($user),
'unsubscribe' => $entityWorkflow->removeSubscriberToFinal($user),
default => throw new LogicException(),
default => throw new \LogicException(),
},
'step' => match ($action) {
'subscribe' => $entityWorkflow->addSubscriberToStep($user),
'unsubscribe' => $entityWorkflow->removeSubscriberToStep($user),
default => throw new LogicException(),
default => throw new \LogicException(),
},
default => throw new BadRequestHttpException('subscribe parameter must be equal to "step" or "final"'),
};

View File

@@ -35,7 +35,6 @@ use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\TransitionBlocker;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
class WorkflowController extends AbstractController
{
@@ -67,11 +66,11 @@ class WorkflowController extends AbstractController
$errors = $this->validator->validate($entityWorkflow, null, ['creation']);
if (count($errors) > 0) {
if (\count($errors) > 0) {
$msg = [];
foreach ($errors as $error) {
/** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
/* @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
$msg[] = $error->getMessage();
}
@@ -294,7 +293,7 @@ class WorkflowController extends AbstractController
$workflow = $this->registry->get($entityWorkflow, $entityWorkflow->getWorkflowName());
$errors = [];
if (count($workflow->getEnabledTransitions($entityWorkflow)) > 0) {
if (\count($workflow->getEnabledTransitions($entityWorkflow)) > 0) {
// possible transition
$usersInvolved = $entityWorkflow->getUsersInvolved();
@@ -310,7 +309,7 @@ class WorkflowController extends AbstractController
[
'transition' => true,
'entity_workflow' => $entityWorkflow,
'suggested_users' => $usersInvolved
'suggested_users' => $usersInvolved,
]
);
@@ -324,12 +323,7 @@ class WorkflowController extends AbstractController
$tb->getParameters()
), iterator_to_array($blockers));
throw $this->createAccessDeniedException(
sprintf(
"not allowed to apply transition {$transition}: %s",
implode(', ', $msgs)
)
);
throw $this->createAccessDeniedException(sprintf("not allowed to apply transition {$transition}: %s", implode(', ', $msgs)));
}
// TODO symfony 5: add those "future" on context ($workflow->apply($entityWorkflow, $transition, $context)
@@ -374,7 +368,7 @@ class WorkflowController extends AbstractController
'transition_form' => isset($transitionForm) ? $transitionForm->createView() : null,
'entity_workflow' => $entityWorkflow,
'transition_form_errors' => $errors,
//'comment_form' => $commentForm->createView(),
// 'comment_form' => $commentForm->createView(),
]
);
}