<?php
namespace AdminBundle\Admin;
use CoreBundle\Entity\Dealer;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use AdminBundle\AdminException;
use CoreBundle\Entity\User;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollectionInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class UserAdmin extends BaseAdmin
{
public function configureRoutes(RouteCollectionInterface $collection): void
{
$collection->remove('delete');
$collection->remove('view');
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
$datagridMapper->add('id');
$datagridMapper->add('username');
$datagridMapper->add('email');
$datagridMapper->add('name');
$datagridMapper->add('last_name');
}
/**
* @param FormMapper $formMapper
* @throws AdminException
*/
protected function configureFormFields(FormMapper $formMapper): void
{
$request = $this->getRequest();
/** @var User $user */
$user = $this->getUser();
$roles = $this->parameterBag->get('security.role_hierarchy.roles');
$roles = array_keys($roles);
$roles = array_combine($roles, $roles);
if (!$user->hasRole('ROLE_SUPER_ADMIN')) {
throw new AdminException('Ви не маєте доступу');
}
$dc = $this->getEntityManager()
->getRepository(Dealer::class)
->findAll();
$dealerChoices = [];
foreach ($dc as $dealer) {
$dealerChoices[$dealer->getName()] = $dealer->getId();
}
$formMapper->with('Пользователь', ['class' => 'col-lg-6']);
$formMapper
->add('name',null, ['label' => 'Имя', 'required' => true])
->add('last_name',null, ['label' => 'Фамиия', 'required' => true])
->add('username', null, ['label' => 'Логин', 'required' => true])
->add('email',null, ['label' => 'E-mail', 'required' => true])
->add('change_dealer_list', ChoiceType::class, [
'label' => 'На які ДЦ може переключатися користувач',
'required' => false,
'multiple' => true,
'expanded' => false,
'choices' => $dealerChoices,
])
->add('roles', ChoiceType::class, [
'label' => 'Роль',
'required' => true,
'multiple' => true,
'choices' => $roles
]);
$formMapper->add('password', null, ['label' => 'Пароль', 'required' => true]);
$formMapper->getFormBuilder()->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event): void {
$data = $event->getData();
$form = $event->getForm();
if ($data['password'] !== $form->get('password')->getData()) {
$data['password'] = password_hash($data['password'], PASSWORD_BCRYPT, ['cost' => 13]);
}
$event->setData($data);
}
);
$formMapper->end();
}
/**
* @param string $context
* @return ProxyQueryInterface
*/
public function configureQuery($context = 'list'): ProxyQueryInterface
{
$query = parent::configureQuery($context);
$alias = $query->getRootAliases()[0];
$query->andWhere($alias.'.roles like \'%ROLE_ADMIN%\' OR '
.$alias.'.roles like \'%ROLE_INSURANCE_AVARKOM%\' OR '
.$alias.'.roles like \'%ROLE_CORP_SALES_MANAGER%\' OR '
.$alias.'.roles like \'%ROLE_CREDIT_MANAGER%\' OR '
.$alias.'.roles like \'%ROLE_ACQUIRING_ADMIN%\' OR '
.$alias.'.roles like \'%ROLE_INSURANCE_ADMIN%\' OR '
.$alias.'.roles like \'%ROLE_DC_MANAGER%\' OR '
.$alias.'.roles like \'%ROLE_TICKET%\' OR '
.$alias.'.roles like \'%ROLE_AUTOMARKET_MANAGER%\' OR '
.$alias.'.roles like \'%ROLE_CONTENT_MANAGER%\' OR '
.$alias.'.roles like \'%ROLE_YAMAHA_SUB_DEALER%\' OR '
.$alias.'.roles like \'%ROLE_SUPER_ADMIN%\''
);
$User = $this->getUser();
if($User?->hasRole("ROLE_SUPER_ADMIN")) {
return $query;
}
$query->andWhere($alias.'.id = :id')->setParameter('id', $User->getId());
return $query;
}
protected function configureListFields(ListMapper $listMapper): void
{
$this->checkByRole(['ROLE_SUPER_ADMIN', 'ROLE_CONTENT_MANAGER','ROLE_DC_MANAGER']);
$dcList = [];
$dc = $this->getEntityManager()->getRepository(Dealer::class)->findAll();
foreach ($dc as $item) {
$dcList[$item->getId()] = $item->getName();
}
$subDcList = [];
$subDc = $this->getEntityManager()->getRepository(\ImporterBundle\Entity\Dealer::class)->findAll();
foreach ($subDc as $item) {
$subDcList[$item->getId()] = $item->getName();
}
$listMapper->addIdentifier('id')
->add('fullName',null,['label' => 'Имя'])
->add('username',null,['label' => 'Login'])
->add('email');
if($this->getUser()->hasRole("ROLE_SUPER_ADMIN")) {
$listMapper
->add('dealer', 'choice', [
'label' => 'ДЦ',
'class' => Dealer::class,
'editable' => true,
'choices' => $dcList
])
->add('sub_dealer', 'choice', [
'label' => 'Суб ДЦ',
'class' => \ImporterBundle\Entity\Dealer::class,
'editable' => true,
'admin_code' => 'admin.sub.contact',
'choices' => $subDcList,
]);
} else {
$listMapper
->add('dealer', null, [
'label' => 'ДЦ',
'class' => Dealer::class,
'editable' => true
])
->add('sub_dealer', null, [
'label' => 'Суб ДЦ',
'class' => \ImporterBundle\Entity\Dealer::class,
'editable' => true,
'admin_code' => 'admin.sub.contact',
]);
}
$listMapper->add('enabled', null, ['editable' => true])
->add('_action', 'actions', [
'label' => 'Действия',
'actions' => [
'edit' => [],
]
])
;
}
/**
* Створити нового користувача
*
* @param User $object
* @throws AdminException
*/
public function prePersist($object): void
{
/**
* @var User $user
*/
$user = $this->getUser();
if (!$user->hasRole('ROLE_SUPER_ADMIN')) {
throw new AdminException("У вас нету доступа");
}
if (empty($object->getName())) {
throw new AdminException("Не вказано поле Имя");
}
if (empty($object->getLastName())) {
throw new AdminException("Не вказано поле Фамиия");
}
if (empty($object->getUsername())) {
throw new AdminException("Не вказано поле Логин");
}
if (empty($object->getEmail())) {
throw new AdminException("Не вказано поле E-mail");
}
if (empty($object->getPassword())) {
throw new AdminException("Не вказано поле Пароль");
}
$model = new UserAdminModel($this->getEntityManager());
if (!empty($model->selectByLogin($object->getUsername()))) {
throw new AdminException("Логин вже використовується");
}
if (!empty($model->selectByEmail($object->getEmail()))) {
throw new AdminException("E-mail вже використовується");
}
$password = $object->getPassword();
$passwordInfo = password_get_info($password);
if ($passwordInfo['algo'] == 0) {
$password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 13]);
}
$object->setEnabled(true);
$object->setPassword($password);
parent::prePersist($object);
}
}