Procházet zdrojové kódy

Refactoring controller

feature/ticket
Fab před 3 roky
rodič
revize
e497cacb9a
11 změnil soubory, kde provedl 215 přidání a 201 odebrání
  1. +3
    -1
      Controller/Config/TaxRateAdminController.php
  2. +40
    -0
      Controller/Merchant/MerchantAdminController.php
  3. +54
    -0
      Controller/Section/SectionAdminController.php
  4. +1
    -55
      Controller/User/GroupUserAdminController.php
  5. +0
    -72
      Controller/User/UserAdminController.php
  6. +53
    -18
      Controller/User/UserMerchantAdminController.php
  7. +37
    -39
      EventSubscriber/User/UserRolesEventSubscriber.php
  8. +8
    -3
      Form/User/UserMerchantFormType.php
  9. +1
    -0
      Resources/translations/admin.fr.yaml
  10. +0
    -13
      Resources/views/admin/user/user_new.html.twig
  11. +18
    -0
      Resources/views/admin/user/usermerchant_edit.html.twig

+ 3
- 1
Controller/Config/TaxRateAdminController.php Zobrazit soubor

@@ -6,10 +6,12 @@ use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Lc\CaracoleBundle\Controller\AbstractAdminController;
use Lc\CaracoleBundle\Controller\AdminControllerTrait;
use Lc\SovBundle\Controller\AbstractAdminController;

abstract class TaxRateAdminController extends AbstractAdminController
{
use AdminControllerTrait;

public function configureCrud(Crud $crud): Crud
{

+ 40
- 0
Controller/Merchant/MerchantAdminController.php Zobrazit soubor

@@ -0,0 +1,40 @@
<?php

namespace Lc\CaracoleBundle\Controller\Merchant;

use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Lc\CaracoleBundle\Controller\AdminControllerTrait;
use Lc\SovBundle\Controller\AbstractAdminController;
use Lc\SovBundle\Field\CKEditorField;
use Lc\SovBundle\Field\StatusField;

abstract class MerchantAdminController extends AbstractAdminController
{
use AdminControllerTrait;

public function configureFields(string $pageName): iterable
{
$panel = parent::configureFields($pageName);

return array_merge(
[
FormField::addPanel('general'),
TextField::new('title'),
NumberField::new('position')
->hideOnForm()
->hideOnIndex(),
CKEditorField::new('description')
->hideOnIndex(),
AssociationField::new('taxRate')
->setRequired(true)
->hideOnIndex(),
StatusField::new('status'),
],
$panel
);
}

}

+ 54
- 0
Controller/Section/SectionAdminController.php Zobrazit soubor

@@ -0,0 +1,54 @@
<?php

namespace Lc\CaracoleBundle\Controller\Section;

use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Lc\CaracoleBundle\Controller\AdminControllerTrait;
use Lc\CaracoleBundle\Model\Section\SectionModel;
use Lc\SovBundle\Controller\AbstractAdminController;
use Lc\SovBundle\Field\BooleanField;
use Lc\SovBundle\Field\CKEditorField;
use Lc\SovBundle\Field\StatusField;

abstract class SectionAdminController extends AbstractAdminController
{
use AdminControllerTrait;

public function configureFields(string $pageName): iterable
{
$panel = parent::configureFields($pageName);

return array_merge(
[
FormField::addPanel('general'),
TextField::new('title'),
//AssociationField::new('merchant'),
ChoiceField::new('cycle')
->setRequired(true)
->setChoices(
[
'Jour' => SectionModel::CYCLE_DAY,
'Semaine' => SectionModel::CYCLE_WEEK,
'Mois' => SectionModel::CYCLE_MONTH,
'Année' => SectionModel::CYCLE_YEAR,
]
),
TextField::new('color')
->setRequired(true)
->hideOnIndex(),
NumberField::new('position')
->hideOnForm()
->hideOnIndex(),
CKEditorField::new('description')
->hideOnIndex(),
StatusField::new('status'),
BooleanField::new('isDefault', 'Section par défaut'),
],
$panel
);
}

}

+ 1
- 55
Controller/User/GroupUserAdminController.php Zobrazit soubor

@@ -2,63 +2,9 @@

namespace Lc\CaracoleBundle\Controller\User;

use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Field\ArrayField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\Field;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Lc\CaracoleBundle\Controller\AbstractAdminController;
use Lc\SovBundle\Controller\AbstractAdminController;

abstract class GroupUserAdminController extends AbstractAdminController
{


public function configureCrud(Crud $crud): Crud
{
return $crud
->setSearchFields(['id', 'title', 'description', 'devAlias', 'position', 'status', 'slug', 'image', 'metaTitle', 'metaDescription', 'oldUrls'])
->setPaginatorPageSize(50)
->setEntityPermission('ROLE_ADMIN')
->overrideTemplate('layout', '@LcCaracole/backend/default/layout/layout.html.twig')
->overrideTemplate('main_menu', '@LcCaracole/backend/default/menu.html.twig')
->overrideTemplate('crud/edit', '@LcCaracole/backend/default/edit.html.twig')
->overrideTemplate('crud/index', '@LcCaracole/backend/default/list.html.twig')
->overrideTemplate('crud/new', '@LcCaracole/backend/default/new.html.twig')
->overrideTemplate('crud/paginator', '@LcCaracole/backend/default/block/paginator.html.twig');
}

public function configureFields(string $pageName): iterable
{
$title = TextField::new('title');
$devAlias = TextField::new('devAlias');
$id = IntegerField::new('id', 'ID');
$description = TextareaField::new('description');
$createdAt = DateTimeField::new('createdAt');
$updatedAt = DateTimeField::new('updatedAt');
$position = NumberField::new('position');
$status = Field::new('status')->setTemplatePath('@LcShop/backend/default/field/toggle.html.twig');
$slug = TextField::new('slug');
$image = TextField::new('image');
$metaTitle = TextField::new('metaTitle');
$metaDescription = TextareaField::new('metaDescription');
$oldUrls = ArrayField::new('oldUrls');
$merchant = AssociationField::new('merchant');
$users = AssociationField::new('users');
$createdBy = AssociationField::new('createdBy');
$updatedBy = AssociationField::new('updatedBy');

if (Crud::PAGE_INDEX === $pageName) {
return [$title, $status];
} elseif (Crud::PAGE_DETAIL === $pageName) {
return [$id, $title, $description, $devAlias, $createdAt, $updatedAt, $position, $status, $slug, $image, $metaTitle, $metaDescription, $oldUrls, $merchant, $users, $createdBy, $updatedBy];
} elseif (Crud::PAGE_NEW === $pageName) {
return [$title, $devAlias];
} elseif (Crud::PAGE_EDIT === $pageName) {
return [$title, $devAlias];
}
}
}

+ 0
- 72
Controller/User/UserAdminController.php Zobrazit soubor

@@ -1,72 +0,0 @@
<?php

namespace Lc\CaracoleBundle\Controller\User;

use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Lc\CaracoleBundle\Resolver\MerchantResolver;
use Lc\CaracoleBundle\Resolver\SectionResolver;
use Lc\SovBundle\Controller\AbstractAdminController;
use Lc\SovBundle\Definition\RolesDefinition;
use Lc\SovBundle\Definition\RolesDefinitionInterface;
use Lc\SovBundle\Doctrine\EntityManager;
use Lc\SovBundle\Model\User\UserInterface;
use Lc\SovBundle\Translation\TranslatorAdmin;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Lc\SovBundle\Controller\User\UserAdminController as SovUserAdminController;

abstract class UserAdminController extends SovUserAdminController
{
public static function getSubscribedServices()
{
return array_merge(parent::getSubscribedServices(), [
'merchant_resolver' => MerchantResolver::class,
'section_resolver' => SectionResolver::class,

]);
}
public function __construct(
SessionInterface $session,
RequestStack $request,
EntityManager $em,
TranslatorAdmin $translatorAdmin,
RolesDefinitionInterface $rolesDefinition,
MerchantResolver $merchantResolver
) {
parent::__construct($session, $request, $em, $translatorAdmin, $rolesDefinition);
}


public function configureCrud(Crud $crud): Crud
{
$crud->overrideTemplate('crud/new', '@LcCaracole/admin/user/user_new.html.twig');
return parent::configureCrud($crud); // TODO: Change the autogenerated stub
}

public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updateUserMerchantRoles($entityManager, $entityInstance);
parent::updateEntity($entityManager,$entityInstance);
}

/* public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updateUserMerchantRoles($entityManager,$entityInstance);
parent::updateEntity($entityManager,$entityInstance);
}*/

protected function updateUserMerchantRoles($entityManager, UserInterface $user){
$userMerchant = $this->get('merchant_resolver')->getUserMerchant($user);

if($userMerchant !== null){
$userMerchant->setRoles($user->getRoles());
//$entityManager->update($userMerchant);
}
}

}

+ 53
- 18
Controller/User/UserMerchantAdminController.php Zobrazit soubor

@@ -7,29 +7,25 @@ use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Field\ArrayField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Lc\CaracoleBundle\Factory\User\UserMerchantFactory;
use Lc\CaracoleBundle\Controller\AdminControllerTrait;
use Lc\CaracoleBundle\Form\User\UserMerchantFormType;
use Lc\CaracoleBundle\Resolver\MerchantResolver;
use Lc\CaracoleBundle\Resolver\SectionResolver;
use Lc\SovBundle\Controller\AbstractAdminController;
use Lc\SovBundle\Factory\User\UserFactory;
use Lc\SovBundle\Field\BooleanField;
use Lc\SovBundle\Model\User\UserInterface;
use Symfony\Component\HttpFoundation\Response;

abstract class UserMerchantAdminController extends AbstractAdminController
{
use AdminControllerTrait;

public function configureFields(string $pageName): iterable
{
return [
TextField::new('user.email'),
TextField::new('user.lastname'),
TextField::new('user.firstname'),
BooleanField::new('active'),
BooleanField::new('creditActive'),
ArrayField::new('roles'),
];
yield TextField::new('user.email');
yield TextField::new('user.lastname');
yield TextField::new('user.firstname');
yield BooleanField::new('active');
yield BooleanField::new('creditActive');
if($this->isGranted('ROLE_SUPER_ADMIN'))yield ArrayField::new('roles');
}

public function new(AdminContext $context): Response
@@ -39,7 +35,7 @@ abstract class UserMerchantAdminController extends AbstractAdminController
$userRepository = $this->em->getRepository(UserInterface::class);
$merchantResolver = $this->get('merchant_resolver');

$userMerchant= $userMerchantFactory->create();
$userMerchant = $userMerchantFactory->create();

$form = $this->createForm(UserMerchantFormType::class, $userMerchant);

@@ -64,8 +60,9 @@ abstract class UserMerchantAdminController extends AbstractAdminController
$this->em->flush();
$this->addFlash('success', $this->translatorAdmin->trans('form.user_merchant.create'));
$url = $this->get(AdminUrlGenerator::class)->setAction(Action::INDEX)->generateUrl();

return $this->redirect($url);
}else{
} else {
//Le user existe, on vérifie si le usemerchant existe aussi
$existingUserMerchant = $merchantResolver->getUserMerchant($existingUser);
if ($existingUserMerchant == null) {
@@ -73,20 +70,58 @@ abstract class UserMerchantAdminController extends AbstractAdminController
$this->em->create($userMerchant);
$this->em->flush();

$this->addFlash('success', $this->translatorAdmin->trans('form.user_merchant.linked'));
$this->addFlash('success', $this->translatorAdmin->trans('form.user_merchant.linked'));
$url = $this->get(AdminUrlGenerator::class)->setAction(Action::INDEX)->generateUrl();
return $this->redirect($url);

}else{
return $this->redirect($url);
} else {
$this->addFlash('error', $this->translatorAdmin->trans('form.user_merchant.already_exist'));
}
}
}

return $this->render(
'@LcCaracole/admin/user/usermerchant_new.html.twig',
[
'form' => $form->createView(),
]
);
}


public function edit(AdminContext $context): Response
{
$userRepository = $this->em->getRepository(UserInterface::class);
$merchantResolver = $this->get('merchant_resolver');

$userMerchant = $context->getEntity()->getInstance();

$form = $this->createForm(UserMerchantFormType::class, $userMerchant);

$form->handleRequest($context->getRequest());

if ($form->isSubmitted() && $form->isValid()) {
$userMerchant = $form->getData();

$userMerchant->getUser()->setEmail($form->get('email')->getData());
$userMerchant->getUser()->setLastName($form->get('lastname')->getData());
$userMerchant->getUser()->setFirstname($form->get('firstname')->getData());

$this->em->update($userMerchant);
$this->em->update($userMerchant->getUser());
$this->em->flush();
$this->addFlash('success', $this->translatorAdmin->trans('form.user_merchant.update'));
$url = $this->get(AdminUrlGenerator::class)->setAction(Action::INDEX)->generateUrl();

return $this->redirect($url);
} else {
$form->get('email')->setData($userMerchant->getUser()->getEmail());
$form->get('lastname')->setData($userMerchant->getUser()->getLastname());
$form->get('firstname')->setData($userMerchant->getUser()->getFirstname());
}

return $this->render(
'@LcCaracole/admin/user/usermerchant_new.html.twig',
'@LcCaracole/admin/user/usermerchant_edit.html.twig',
[
'form' => $form->createView(),
]

+ 37
- 39
EventSubscriber/User/UserRolesEventSubscriber.php Zobrazit soubor

@@ -3,72 +3,77 @@
namespace Lc\CaracoleBundle\EventSubscriber\User;

use Doctrine\ORM\EntityManagerInterface;
use Lc\CaracoleBundle\Doctrine\Extension\FilterMerchantInterface;
use Lc\CaracoleBundle\Doctrine\Extension\FilterMultipleMerchantsInterface;
use Lc\CaracoleBundle\Doctrine\Extension\FilterSectionInterface;
use Lc\CaracoleBundle\Model\User\UserMerchantInterface;
use Lc\CaracoleBundle\Resolver\MerchantResolver;
use Lc\CaracoleBundle\Resolver\SectionResolver;
use Lc\SovBundle\Definition\RolesDefinition;
use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
use Lc\SovBundle\Model\User\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;

class UserRolesEventSubscriber implements EventSubscriberInterface
{
protected $em;
protected $tokenStorage;
protected $security;
protected $router;
protected $merchantResolver;
protected $sectionResolver;

public function __construct(
TokenStorageInterface $tokenStorage,
EntityManagerInterface $entityManager,
Security $security,
MerchantResolver $merchantResolver,
SectionResolver $sectionResolver
RouterInterface $router,
MerchantResolver $merchantResolver
) {
$this->em = $entityManager;
$this->tokenStorage = $tokenStorage;
$this->security = $tokenStorage;
$this->router = $router;
$this->merchantResolver = $merchantResolver;
$this->sectionResolver = $sectionResolver;
}

public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['setUserRoles'],
KernelEvents::REQUEST => ['setUserRolesFromKernelRequest'],
SecurityEvents::INTERACTIVE_LOGIN => ['setUserRolesAuthenticationSuccess'],
];
}

public function setUserRoles(RequestEvent $event)
public function setUserRolesFromKernelRequest(RequestEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
if ($this->setUserRoles($event->getRequest())) {
$response = new RedirectResponse($this->router->generate('admin_dashboard'));
$event->setResponse($response);
}
}

public function setUserRolesAuthenticationSuccess(InteractiveLoginEvent $interactiveLoginEvent)
{
$this->setUserRoles($interactiveLoginEvent->getRequest());
}


public function setUserRoles(Request $request): bool
{
if ($this->tokenStorage && $this->tokenStorage->getToken()) {
$token = $this->tokenStorage->getToken();
$sessionUser = $token->getUser();
if($sessionUser instanceof UserInterface) {

$userMerchant = $this->merchantResolver->getUserMerchant($sessionUser) ;
if ($sessionUser instanceof UserInterface) {
$userMerchant = $this->merchantResolver->getUserMerchant($sessionUser);

if($userMerchant) {
if ($userMerchant) {
$roles = $userMerchant->getRoles();
}
else {
$roles = [RolesDefinition::ROLE_USER] ;
} else {
$roles = [RolesDefinition::ROLE_USER];
}

if ($roles != $sessionUser->getRoles()) {
@@ -76,26 +81,19 @@ class UserRolesEventSubscriber implements EventSubscriberInterface
$this->em->update($sessionUser);
$this->em->flush();

$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken(
$token = new UsernamePasswordToken(
$sessionUser,
null,
'main',
$sessionUser->getRoles()
);
$this->security->setToken($token);
$this->tokenStorage->setToken($token);

return true;
}
}
/*
// This check can be just `is_object` like in symfony core
// we're explicit about the class used
if ($sessionUser instanceof UserInterface) {
/* if ($this->merchantResolver->getCurrent()->getId() == 2) {
$sessionUser->setRoles(array('ROLE_ADMIN', 'ROLE_BEST_USER'));
}
$this->tokenStorage->setToken(
new PostAuthenticationGuardToken($sessionUser, 'main', $sessionUser->getRoles())
);
}*/

return false;
}
}


+ 8
- 3
Form/User/UserMerchantFormType.php Zobrazit soubor

@@ -3,6 +3,7 @@
namespace Lc\CaracoleBundle\Form\User;

use Lc\CaracoleBundle\Model\User\UserMerchantInterface;
use Lc\SovBundle\Definition\RolesDefinition;
use Lc\SovBundle\Definition\RolesDefinitionInterface;
use Lc\SovBundle\Doctrine\EntityManager;
use Lc\SovBundle\Model\User\UserInterface;
@@ -15,21 +16,25 @@ use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

class UserMerchantFormType extends AbstractType
{
protected $em;
protected $rolesDefinition;
protected $translatorAdmin;
protected $authorizationChecker;

public function __construct(
EntityManager $em,
TranslatorAdmin $translatorAdmin,
RolesDefinitionInterface $rolesDefinition
RolesDefinitionInterface $rolesDefinition,
AuthorizationCheckerInterface $authorizationChecker
) {
$this->em = $em;
$this->rolesDefinition = $rolesDefinition;
$this->translatorAdmin = $translatorAdmin;
$this->authorizationChecker = $authorizationChecker;
}

public function buildForm(FormBuilderInterface $builder, array $options)
@@ -64,7 +69,7 @@ class UserMerchantFormType extends AbstractType
'creditActive',
CheckboxType::class,
array(
'required'=>false
'required' => false,
)
);

@@ -73,7 +78,7 @@ class UserMerchantFormType extends AbstractType
ChoiceType::class,
array(
'choices' => $this->rolesDefinition->getRolesList(),
'multiple'=> true
'multiple' => true,
)

);

+ 1
- 0
Resources/translations/admin.fr.yaml Zobrazit soubor

@@ -7,6 +7,7 @@ menu:
admin_merchant: Marchands
admin_section: Sections
admin_tva: TVA
user_merchant_index: Utilisateurs

flash_message:
settings_saved: Paramètres mis à jour

+ 0
- 13
Resources/views/admin/user/user_new.html.twig Zobrazit soubor

@@ -1,13 +0,0 @@
{# @var ea \EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext #}
{# @var entity \EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto #}
{% extends '@LcSov/adminlte/crud/new.html.twig' %}
{% import '@LcSov/adminlte/macro/callout.html.twig' as cm %}
{% block aside %}
{{ cm.callout('info', 'Il est possible que l\'utilisateur existe déjà dans notre sytème, si c\'est le cas, importez le !', 'Utilisateur déjà existant ?') }}

{% set url = ea_url()
.setController('App\\Controller\\User\\UserMerchantAdminController')
.setAction('new')
%}
<a href="{{ url }}">Importer</a>
{% endblock %}

+ 18
- 0
Resources/views/admin/user/usermerchant_edit.html.twig Zobrazit soubor

@@ -0,0 +1,18 @@
{% extends '@LcCaracole/adminlte/layout.html.twig' %}

{% block content_title %}
{{ 'edit'|lc_trans_admin_title(ea.getEntity().getFqcn(), {id: ea.getEntity().getInstance().getId()}) }}
{% endblock %}

{% block main %}
<div class="col-8">
{% embed '@LcSov/adminlte/embed/card.html.twig' %}
{% block header_wrapper %}{% endblock %}
{% block body %}
{% form_theme form '@LcSov/adminlte/crud/form_theme.html.twig' %}
{{ form(form) }}
{% endblock %}
{% block footer_wrapper %}{% endblock %}
{% endembed %}
</div>
{% endblock main %}

Načítá se…
Zrušit
Uložit