src/Application/Sonata/UserBundle/Admin/UserAdmin.php line 37

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the Sonata Project package.
  5.  *
  6.  * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace App\Application\Sonata\UserBundle\Admin;
  12. use App\Application\Sonata\UserBundle\Entity\User;
  13. use App\Enums\UFEnum;
  14. use App\Services\ImageCachingManager;
  15. use FOS\UserBundle\Model\UserManagerInterface;
  16. use Sonata\AdminBundle\Admin\AbstractAdmin;
  17. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  18. use Sonata\AdminBundle\Datagrid\ListMapper;
  19. use Sonata\AdminBundle\Form\FormMapper;
  20. use Sonata\AdminBundle\Form\Type\ModelType;
  21. use Sonata\AdminBundle\Show\ShowMapper;
  22. use Sonata\Form\Type\CollectionType;
  23. use Sonata\Form\Type\DatePickerType;
  24. use Sonata\UserBundle\Form\Type\SecurityRolesType;
  25. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  26. use Symfony\Component\Form\Extension\Core\Type\FileType;
  27. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  28. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  29. use Symfony\Component\Form\Extension\Core\Type\TelType;
  30. use Symfony\Component\HttpFoundation\File\UploadedFile;
  31. use Symfony\Component\Security\Core\Security;
  32. class UserAdmin extends AbstractAdmin
  33. {
  34.     /**
  35.      * @var Security
  36.      */
  37.     private $security;
  38.     /**
  39.      * @var UserManagerInterface
  40.      */
  41.     protected $userManager;
  42.     public function __construct($code$class$baseControllerNameSecurity $security)
  43.     {
  44.         parent::__construct($code$class$baseControllerName);
  45.         $this->security $security;
  46.     }
  47.     /**
  48.      * {@inheritdoc}
  49.      */
  50.     public function getFormBuilder()
  51.     {
  52.         $this->formOptions['data_class'] = $this->getClass();
  53.         $options $this->formOptions;
  54.         $options['validation_groups'] = (!$this->getSubject() || null === $this->getSubject()->getId()) ? 'Registration' 'Profile';
  55.         $formBuilder $this->getFormContractor()->getFormBuilder($this->getUniqid(), $options);
  56.         $this->defineFormBuilder($formBuilder);
  57.         return $formBuilder;
  58.     }
  59.     /**
  60.      * {@inheritdoc}
  61.      */
  62.     public function getExportFields()
  63.     {
  64.         // avoid security field to be exported
  65.         return array_filter(parent::getExportFields(), function ($v) {
  66.             return !in_array($v, ['password''salt']);
  67.         });
  68.     }
  69.     /**
  70.      * {@inheritdoc}
  71.      */
  72.     public function preUpdate($user): void
  73.     {
  74.         $this->getUserManager()->updateCanonicalFields($user);
  75.         $this->getUserManager()->updatePassword($user);
  76.     }
  77.     /**
  78.      * @return UserManagerInterface
  79.      */
  80.     public function getUserManager()
  81.     {
  82.         return $this->userManager;
  83.     }
  84.     /**
  85.      * @param UserManagerInterface $userManager
  86.      */
  87.     public function setUserManager(UserManagerInterface $userManager): void
  88.     {
  89.         $this->userManager $userManager;
  90.     }
  91.     /**
  92.      * {@inheritdoc}
  93.      */
  94.     protected function configureListFields(ListMapper $listMapper): void
  95.     {
  96.         $listMapper
  97.             ->addIdentifier('username')
  98.             ->add('email')
  99.             ->add('groups')
  100.             ->add('enabled'null, ['editable' => true])
  101.             ->add('createdAt')
  102.         ;
  103.         if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
  104.             $listMapper
  105.                 ->add('impersonating''string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
  106.             ;
  107.         }
  108.     }
  109.     /**
  110.      * {@inheritdoc}
  111.      */
  112.     protected function configureDatagridFilters(DatagridMapper $filterMapper): void
  113.     {
  114.         $filterMapper
  115.             ->add('id')
  116.             ->add('username')
  117.             ->add('firstname')
  118.             ->add('lastname')
  119.             ->add('email')
  120.             ->add('gender')
  121.             ->add('dateOfBirth')
  122.             ->add('groups')
  123.         ;
  124.     }
  125.     /**
  126.      * {@inheritdoc}
  127.      */
  128.     protected function configureShowFields(ShowMapper $showMapper): void
  129.     {
  130.         $showMapper
  131.             ->with('General')
  132.                 ->add('username')
  133.                 ->add('email')
  134.                 ->add('cpfCnpj')
  135.             ->end()
  136.             ->with('Groups')
  137.                 ->add('groups')
  138.             ->end()
  139.             ->with('Profile')
  140.                 ->add('firstname')
  141.                 ->add('lastname')
  142.                 ->add('dateOfBirth')
  143.                 ->add('gender')
  144.                 ->add('phone')
  145.                 ->add('uf')
  146.             ->end()
  147.         ;
  148.     }
  149.     /**
  150.      * {@inheritdoc}
  151.      */
  152.     protected function configureFormFields(FormMapper $formMapper): void
  153.     {
  154.         /** @var User $user */
  155.         $user $this->getSubject();
  156.         $avatarThumb '<img src="' $user->getAvatar() . '" class="admin-preview img-thumbnail img-circle" style="max-width:150px;max-height:150px;"/>';
  157.         if ($this->isGranted('ROLE_SUPER_ADMIN')) {
  158.             $formMapper
  159.                 ->tab('User')
  160.                     ->with('Profile', ['class' => 'col-md-6'])->end()
  161.                     ->with('General', ['class' => 'col-md-6'])->end()
  162.                 ->end()
  163.                 ->tab('Security')
  164.                     ->with('Status', ['class' => 'col-md-4'])->end()
  165.                     ->with('Groups', ['class' => 'col-md-4'])->end()
  166.                 ->end();
  167.         } else {
  168.             $formMapper
  169.                 ->tab('User')
  170.                     ->with('Profile', ['class' => 'col-md-6'])->end()
  171.                     ->with('General', ['class' => 'col-md-6'])->end()
  172.                 ->end();
  173.         }
  174.         // define group zoning
  175. //        $formMapper
  176. //            ->tab('User')
  177. //                ->with('Profile', ['class' => 'col-md-6'])->end()
  178. //                ->with('General', ['class' => 'col-md-6'])->end()
  179. //            ->end()
  180. //            ->tab('Security')
  181. //                ->with('Status', ['class' => 'col-md-4'])->end()
  182. //                ->with('Groups', ['class' => 'col-md-4'])->end()
  183. //            ->end();
  184. //        if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  185. //            $formMapper
  186. //                ->tab('Security')
  187. //                    ->with('Roles', ['class' => 'col-md-12'])->end()
  188. //                ->end()
  189. //            ;
  190. //        }
  191.         $now = new \DateTime();
  192.         $genderOptions = [
  193.             'choices' => call_user_func([$this->getUserManager()->getClass(), 'getGenderList']),
  194.             'required' => true,
  195.             'expanded' => true,
  196.             'multiple' => false,
  197.             'translation_domain' => $this->getTranslationDomain(),
  198.         ];
  199.         if ($this->isGranted('ROLE_SUPER_ADMIN')) {
  200.             $formMapper
  201.                 ->tab('User')
  202.                 ->with('General')
  203.                 ->add('franquia'ModelType::class, [
  204.                     'label' => 'Franquia/Empresa',
  205.                     'required' => true,
  206.                     'expanded' => false,
  207.                     'multiple' => false,
  208.                 ])
  209.                 ->add('username')
  210.                 ->add('email')
  211.                 ->add('cpfCnpj'null, ['required' => false'label' => 'CPF'])
  212.                 ->add('plainPassword'RepeatedType::class, array(
  213.                     'type' => PasswordType::class,
  214.                     'options' => array('translation_domain' => 'FOSUserBundle'),
  215.                     'first_options' => array('label' => 'form.password'),
  216.                     'second_options' => array('label' => 'form.password_confirmation'),
  217.                     'invalid_message' => 'fos_user.password.mismatch',
  218.                     'required' => (!$this->getSubject() || is_null($this->getSubject()->getId())),
  219.                 ))
  220.                 ->end()
  221.                 ->with('Profile')
  222. //                    ->add('avatarFile', FileType::class, array_merge([
  223. //                        'data_class' => null,
  224. //                        'required' => false,
  225. //                        'label' => "Avatar",
  226. //                    ], $user->getAvatar() != '' ? ['help' => $avatarThumb] : []))
  227.                 ->add('firstname'null, ['required' => true])
  228.                 ->add('lastname'null, ['required' => false])
  229.                 ->add('gender'ChoiceType::class, $genderOptions)
  230.                 ->add('dateOfBirth'DatePickerType::class , [
  231.                     'years' => range(1900$now->format('Y')),
  232.                     'dp_min_date' => '1-1-1900',
  233.                     'dp_max_date' => $now->format('c'),
  234.                     'required' => false,
  235.                 ])
  236.                 ->add('phone'TelType::class, ['required' => false])
  237.                 ->add('uf'ChoiceType::class, [
  238.                     'label' => 'UF',
  239.                     'choices' => UFEnum::getAssociatedValues(),
  240.                 ])
  241.                 ->end()
  242.                 ->end();
  243.         } else {
  244.             $formMapper
  245.                 ->tab('User')
  246.                 ->with('General')
  247.                 ->add('cpfCnpj'null, ['required' => false'label' => 'CPF'])
  248.                 ->add('plainPassword'RepeatedType::class, array(
  249.                     'type' => PasswordType::class,
  250.                     'options' => array('translation_domain' => 'FOSUserBundle'),
  251.                     'first_options' => array('label' => 'form.password'),
  252.                     'second_options' => array('label' => 'form.password_confirmation'),
  253.                     'invalid_message' => 'fos_user.password.mismatch',
  254.                     'required' => (!$this->getSubject() || is_null($this->getSubject()->getId())),
  255.                 ))
  256.                 ->end()
  257.                 ->with('Profile')
  258. //                    ->add('avatarFile', FileType::class, array_merge([
  259. //                        'data_class' => null,
  260. //                        'required' => false,
  261. //                        'label' => "Avatar",
  262. //                    ], $user->getAvatar() != '' ? ['help' => $avatarThumb] : []))
  263.                 ->add('firstname'null, ['required' => true])
  264.                 ->add('lastname'null, ['required' => false])
  265.                 ->add('gender'ChoiceType::class, $genderOptions)
  266.                 ->add('dateOfBirth'DatePickerType::class , [
  267.                     'years' => range(1900$now->format('Y')),
  268.                     'dp_min_date' => '1-1-1900',
  269.                     'dp_max_date' => $now->format('c'),
  270.                     'required' => false,
  271.                 ])
  272.                 ->add('phone'TelType::class, ['required' => false])
  273.                 ->add('uf'ChoiceType::class, [
  274.                     'label' => 'UF',
  275.                     'choices' => UFEnum::getAssociatedValues(),
  276.                 ])
  277.                 ->end()
  278.                 ->end();
  279.         }
  280.         if($this->security->isGranted('ROLE_SUPER_ADMIN')){
  281.             $formMapper
  282.                 ->tab('Security')
  283.                 ->with('Status')
  284.                 ->add('enabled'null, ['required' => false])
  285.                 ->end()
  286.                 ->with('Groups')
  287.                 ->add('groups'ModelType::class, [
  288.                     'required' => false,
  289.                     'expanded' => true,
  290.                     'multiple' => true,
  291.                 ])
  292.                 ->end()
  293.                 ->end();
  294.         }
  295.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  296.             $formMapper
  297.                 ->tab('Security')
  298.                     ->with('Roles',['class' => 'col-md-12'])
  299.                         ->add('realRoles'SecurityRolesType::class, [
  300.                             'label' => false,
  301.                             'expanded' => true,
  302.                             'multiple' => true,
  303.                             'required' => false,
  304.                         ])
  305.                     ->end()
  306.                 ->end()
  307.             ;
  308.         }
  309.     }
  310.     public function postPersist($object)
  311.     {
  312.         //return $this->manageFilesUpload($object);
  313.     }
  314.     public function postUpdate($object)
  315.     {
  316.         //return $this->manageFilesUpload($object);
  317.     }
  318.     /**
  319.      * @param User $obj
  320.      * @return User
  321.      */
  322.     private function manageFilesUpload($obj)
  323.     {
  324.         $file $obj->getAvatarFile();
  325.         $container $this->getConfigurationPool()->getContainer();
  326.         // Upload File and create thumbnail
  327.         if ($file instanceof UploadedFile) {
  328.             $obj $container->get(ImageCachingManager::class)
  329.                 ->processUploadAndFilter($obj'avatarOriginal''avatar'$file'thumb_400px');
  330.         }
  331.         return $obj;
  332.     }
  333. }