2 years ago

#53115

test-img

MrFireFerid

Decrypt data from database in my Index page with EasyAdminBundle3 and Symfony5

I create a service to encrypt and decrypt my data in my database. So when I create a new Fiche or update one, I encrypt the name and the surname Here my subscriber FicheEntitySubscriber :

class FicheEntitySubscriber implements EventSubscriberInterface
{
    private $security;
    private $encryptionService;

    public function __construct(Security $security, EncryptionService $encryptionService)
    {
        $this->security = $security;
        $this->encryptionService = $encryptionService;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            BeforeEntityPersistedEvent::class => ['setFicheEntity', 10],
            BeforeEntityUpdatedEvent::class => ['setFicheEntity', 10]
        ];
    }

/**
     * @throws Exception
     */
    public function setFicheEntity(AbstractLifecycleEvent $event)
    {
        $entity = $event->getEntityInstance();

        if (!($entity instanceof FicheEntity)) {
            return;
        }

        if ($event instanceof BeforeEntityPersistedEvent) {
            $entity->setUtilisateur($this->security->getUser());
        }

        $entity->setNom($this->encryptionService->encrypt_decrypt('encrypt', mb_strtoupper($entity->getNom())));
        $entity->setPrenom($this->encryptionService->encrypt_decrypt('encrypt', mb_strtoupper($entity->getPrenom())));
       
    }
}

Here my FicheController :

class FicheEntityCrudController extends AbstractCrudController
{
    private $_adminContextFactory;
    private $encryptService;
    private $ficheEntityRepo;

    public function __construct(AdminContextFactory $adminContextFactory, EncryptionService $encryptionService, FicheEntityRepository $ficheEntityRepo)
    {
        $this->_adminContextFactory = $adminContextFactory;
        $this->encryptService = $encryptionService;
        $this->ficheEntityRepo = $ficheEntityRepo;
    }

    public static function getEntityFqcn(): string
    {
        return FicheEntity::class;
    }

    public function configureCrud(Crud $crud): Crud
    {
        return $crud
            ->setEntityLabelInPlural('Fiches')
            ->setEntityLabelInSingular('Fiche informative')
            ->setSearchFields(['nom', 'prenom', 'nomAntibio'])
            ->setPaginatorPageSize(10)
            ->setPaginatorRangeSize(2);
    }

    public function configureFilters(Filters $filters): Filters
    {
        return $filters
            ->add(TextFilter::new('nomAntibio')->setLabel('Nom ATB'))
            ->add(DateTimeFilter::new('dateDebut')->setLabel('Date Debut'))
            ->add(DateTimeFilter::new('dateRappel3Jour')->setLabel('Rappel 3e Jour'))
            ->add(DateTimeFilter::new('dateRappel7Jour')->setLabel('Rappel 7e Jours'));
    }

    public function configureActions(Actions $actions): Actions
    {
        $export = Action::new('exportAction', 'Export')
            ->setIcon('fa fa-download')
            ->linkToCrudAction('exportAction')
            ->setCssClass('btn')
            ->createAsGlobalAction();

        return $actions
            ->add(Crud::PAGE_INDEX, $export);
    }

    public function exportAction(Request $request): Response
    {
        $context = $this->_getEasyAdminRefererContext($request);

        $searchDto = $this->_adminContextFactory->getSearchDto($request, $context->getCrud());
        $fields = FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
        $filters = $this->get(FilterFactory::class)->create($context->getCrud()->getFiltersConfig(), $fields, $context->getEntity());


        $result = $this->createIndexQueryBuilder(
            $searchDto, $context->getEntity(), $fields, $filters
        )
            ->getQuery()->getResult();

        $data = [];
        /**
         * @var $record FicheEntity
         */
        foreach ($result as $record) {
            $data[] = [
                'Nom Complet' => $record->getFullname(),
                'Chambre' => $record->getChambre(),
                'Date Debut' => $record->getDateDebut()->format('y-m-d'),
                'Duree ATB' => $record->getDureeJour(),
                'Nom ATB' => $record->getNomAntibio(),
                'Rappel 3e Jour' => ($record->getDateRappel3Jour() !== null ? $record->getDateRappel3Jour()->format('y-m-d') : $record->getDateRappel3Jour()),
                'Réévalué' => ($record->getDateRappel3Jour() !== null ? ($record->getReevalue() === true ? 'oui' : 'non') : ''),
                'Rappel 7e Jour' => ($record->getDateRappel7Jour() !== null ? $record->getDateRappel7Jour()->format('y-m-d') : $record->getDateRappel7Jour()),
                'Justifié' => ($record->getDateRappel7Jour() !== null ? ($record->getJustifie() === true ? 'oui' : 'non') : ''),
                'Pathologie' => $record->getPathologie(),
                'Hospitalier' => ($record->getHospitalier() === true ? 'oui' : '')
            ];

        }

        $filename = 'export_fiche_' . date_create()->format('d-m-y H:i:s') . '.csv';

        $serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);
        $response = new Response($serializer->encode($data, CsvEncoder::FORMAT));
        $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
        $response->headers->set('Content-Disposition', "attachment; filename=\"$filename\"");

        return $response;
    }

    private function _getEasyAdminRefererContext(Request $request)
    {

        \parse_str(\parse_url($request->query->get(EA::REFERRER))[EA::QUERY], $referrerQuery);
        if (array_key_exists(EA::FILTERS, $referrerQuery)) {
            $request->query->set(EA::FILTERS, $referrerQuery);
        }

        return $request->attributes->get(EA::CONTEXT_REQUEST_ATTRIBUTE);
    }

    public function configureFields(string $pageName): iterable
    {
        return [
            IntegerField::new('id')->hideOnForm()->hideOnIndex(),
            TextField::new('nom')->hideOnIndex()->setColumns(6),
            TextField::new('prenom')->hideOnIndex()->setColumns(6),
            TextField::new('fullname')->setLabel('Nom complet')->hideOnForm(),
            IntegerField::new('chambre')->setColumns(4),
            TextField::new('nomAntibio')->setLabel('Nom ATB')->setColumns(4),
            IntegerField::new('dureeJour')->setLabel('Durée ATB TTT')->setColumns(4),
            DateField::new('dateDebut'),
            DateField::new('dateRappel3Jour')->setLabel('Rappel 3e Jour')->hideOnForm(),
            BooleanField::new('reevalue')->setLabel('Réévalué')->hideOnForm(),
            DateField::new('dateRappel7Jour')->setLabel('Rappel 7e Jour')->hideOnForm(),
            BooleanField::new('justifie')->setLabel('Justifié')->hideOnForm(),
            TextField::new('pathologie'),
            AssociationField::new('utilisateur', 'Admin')->setLabel('Utilisateur')->hideOnForm(),
            BooleanField::new('hospitalier')

        ];
    }

My issue is that when I display my list of fiches, I want to decrypt the encrypted data, for now I try :

  • use the AfterEntityBuiltEvent (did not working)
  • listen on Event postLoad
  • create an custom action

but none of these are working. Does someone try something similar ? Thanks in advance

php

encryption

event-handling

symfony5

easyadmin

0 Answers

Your Answer

Accepted video resources