src/Controller/ProfileController.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Form\AccountType;
  4. use App\Form\PasswordChangeType;
  5. use App\Repository\PublicationRepository;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. //use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Psr\Container\ContainerInterface;
  9. use Sulu\Bundle\CommunityBundle\Controller\AbstractController;
  10. use Sulu\Bundle\MediaBundle\Api\Media;
  11. use Sulu\Bundle\MediaBundle\Entity\MediaInterface;
  12. use Sulu\Bundle\SecurityBundle\Entity\User;
  13. use Sulu\Component\Media\SystemCollections\SystemCollectionManager;
  14. use Sulu\Component\Media\SystemCollections\SystemCollectionManagerInterface;
  15. use Symfony\Component\Form\FormInterface;
  16. use Symfony\Component\HttpFoundation\File\UploadedFile;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  21. use Sulu\Bundle\MediaBundle\Media\Manager\MediaManagerInterface;
  22. use Symfony\Component\Serializer\SerializerInterface;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. class ProfileController extends AbstractController
  25. {
  26.     private $entityManager;
  27.     private $encoder;
  28.     protected $container;
  29.     private $mediaManager;
  30.     private $collectionManager;
  31.     public function __construct(EntityManagerInterface $entityManagerUserPasswordEncoderInterface $encoderContainerInterface $container,MediaManagerInterface $mediaManager,SystemCollectionManagerInterface $collectionManager)
  32.     {
  33.         $this->entityManager $entityManager;
  34.         $this->encoder=$encoder;
  35.         $this->container=$container;
  36.         $this->mediaManager=$mediaManager;
  37.         $this->collectionManager=$collectionManager;
  38.         if (is_callable('parent::__construct')) {
  39.             parent::__construct();
  40.         }
  41.     }
  42.     /**
  43.      * @Route("/profile/profile-Publications", name="profile_publications")
  44.      */
  45.     public function profilePublications(PublicationRepository  $publicationRepository)
  46.     {
  47.         $user=$this->getUser();
  48.         $publications$publicationRepository->findBy(['user' => $user->getId()]);
  49.         return $this->render('Profile/profil-publications.html.twig',['publications'=>$publications'user'=>$user]);
  50.     }
  51.     /**
  52.      * @Route("/profile/profile-Account", name="profile_account")
  53.      */
  54.     public function profilAccountSettings(Request $request)
  55.     {
  56.         /** @var User $user */
  57.        $user=$this->getUser();
  58.        $form $this->createForm(AccountType::class, $user);
  59.        $form->handleRequest($request);
  60.        $entityManager $this->getDoctrine()->getManager();
  61.        if ($form->isSubmitted() && $form->isValid()) {
  62.            $fullName=trim($form->get('fullName')->getData());
  63.            $firstname=$fullName;
  64.            $lastname=$fullName;
  65.            if(str_contains($fullName' ')){
  66.                $fullName=explode(' ',$fullName);
  67.                $firstname=$fullName[0];
  68.                if(count($fullName)==1){
  69.                    $firstname=$fullName[1];
  70.                    $lastname=$fullName[1];
  71.                } elseif (count($fullName)==2){
  72.                    $lastname=$fullName[1];
  73.                }else{
  74.                    array_shift($fullName);
  75.                    $lastname=implode(" ",$fullName);
  76.                }
  77.            }
  78.           $user->setFirstName($firstname);
  79.           $user->setLastName($lastname);
  80.           $user->setEmail($form->get('email')->getData());
  81.            $this->saveMediaFields($form$user$request->getLocale());
  82.            if($form->has('avatar')){
  83.                $user->setPictureSocial(null);
  84.            }
  85.            $entityManager->persist($user);
  86.           $entityManager->flush();
  87.           //$this->addFlash('success', 'You have successfully modified your account!');
  88.        }
  89.         return $this->render('Profile/profile-settings-account.html.twig', ['form'=> $form->createView(), 'user'=>$user]);
  90.     }
  91. ///////////////////////////
  92. /**
  93.      * @Route("/api/profile/profile-Account", name="update", methods={"POST"})
  94.      */
  95.     public function profilAccountSettingsAPI(Request $request)
  96.     {
  97.         $data json_decode($request->getContent(), true);
  98.         $user $this->entityManager->getRepository("App\Entity\User")->findOneBy(['username' => $data['email']]);
  99.     
  100.         if ($user) {
  101.             $user->setFullname($data['name']);
  102.             $user->setCountry($data['country']);
  103.     
  104.             $this->entityManager->persist($user); // Use $this->entityManager
  105.             $this->entityManager->flush(); // Use $this->entityManager
  106.     
  107.             return new JsonResponse([
  108.                 'FullName' => $user->getFullName(),
  109.             'Email' => $user->getUserName(),
  110.             'Country' => $user->getCountry()]);
  111.         } else {
  112.             return new JsonResponse("User not found"404);
  113.         }
  114.     }
  115.      /**
  116.      * @Route("/api/update-password", name="update_password", methods={"POST"})
  117.      */
  118.     public function updatePassword(Request $requestUserPasswordEncoderInterface $encoder): Response
  119. {
  120.     $data json_decode($request->getContent(), true);
  121.     $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['username' => $data['email']]);
  122.     
  123.     if (!$user) {
  124.         return $this->json(['message' => 'User not found'], Response::HTTP_NOT_FOUND);
  125.     }
  126.     $currentPassword $data['current_password'];
  127.     $newPassword $data['new_password'];
  128.     if (!$encoder->isPasswordValid($user$currentPassword)) {
  129.         return $this->json(['message' => 'Current password is incorrect'], Response::HTTP_UNAUTHORIZED);
  130.     }
  131.     $hashedPassword $encoder->encodePassword($user$newPassword);
  132.     $user->setPassword($hashedPassword);
  133.     
  134.     $entityManager $this->getDoctrine()->getManager();
  135.     $entityManager->flush();
  136.     return $this->json(['message' => 'Password updated successfully'], Response::HTTP_OK);
  137. }
  138. ////////////////////////////////
  139.     /**
  140.      * @Route("/profile/profile-Account-Deactivate", name="profile_deactivation")
  141.      */
  142.     public function profilAccountDeactivation(Request $request)
  143.     {
  144.        $entityManager $this->getDoctrine()->getManager();
  145.        $user=$this->getUser();
  146.        $deactivation_reason=$request->request->get('deactivation-select');
  147.         if($deactivation_reason){
  148.             $user->setDeleted(true);
  149.             $user->setDeletedAt(new \DateTime());
  150.             $user->setDeactivationReason($deactivation_reason);
  151.             $entityManager->persist($user);
  152.             $entityManager->flush();
  153.             return $this->redirectToRoute("sulu_community.logout");
  154.         }
  155.         return $this->redirectToRoute("/");
  156.     }
  157.     /**
  158.      * @Route("/profile/profile-Security", name="profil_security")
  159.      */
  160.     public function profilSecuritySettings(Request $request)
  161.     {
  162.         $user=$this->getUser();
  163.         $form $this->createForm(PasswordChangeType::class, $user);
  164.         $form->handleRequest($request);
  165.         if ($form->isSubmitted() && $form->isValid()) {
  166.             $current_password$form->get('cuurent_password')->getData();
  167.             $new_password$form->get('plainPassword')->getData();
  168.             if($this->encoder->isPasswordValid($user$current_password)){
  169.                 $user->setPassword(  $this->encoder->encodePassword($user$new_password));
  170.                 $this->entityManager->persist($user);
  171.                 $this->entityManager->flush();
  172.                 $this->addFlash('success''You have successfully modified your password!');
  173.             }else{
  174.                 $this->addFlash('error''Your password is incorrect');
  175.             }
  176.         }
  177.         return $this->render('Profile/profile-settings-security.html.twig', ['form'=> $form->createView(), 'user'=>$user]);
  178.     }
  179.     /**
  180.      * @Route("/profile/profile-Notifications", name="profile_notifications")
  181.      */
  182.     public function profilNotificationsSettings()
  183.     {
  184.         $user=$this->getUser();
  185.         return $this->render('Profile/profile-settings-notifications.html.twig', ['user'=>$user]);
  186.     }
  187.     private function saveMediaFields(FormInterface $formUser $userstring $locale): void
  188.     {
  189.         $this->saveAvatar($form$user$locale);
  190.     }
  191.     protected function saveAvatar(FormInterface $formUser $userstring $locale): ?Media
  192.     {
  193.         if (!$form->has('avatar')) {
  194.             return null;
  195.         }
  196.         /** @var UploadedFile|null $uploadedFile */
  197.         $uploadedFile $form->get('avatar')->getData();
  198.         if (null === $uploadedFile) {
  199.             return null;
  200.         }
  201.         $avatar $user->getContact()->getAvatar();
  202.         /** @var MediaInterface|null $avatar */
  203.         $apiMedia $this->saveMedia($uploadedFilenull !== $avatar $avatar->getId() : null$locale$user->getId());
  204.         $user->getContact()->setAvatar($apiMedia->getEntity());
  205.         return $apiMedia;
  206.     }
  207.     private function saveMedia(UploadedFile $uploadedFile, ?int $idstring $locale, ?int $userId): Media
  208.     {
  209.         return $this->mediaManager->save(
  210.             $uploadedFile,
  211.             [
  212.                 'id' => $id,
  213.                 'locale' => $locale,
  214.                 'title' => $uploadedFile->getClientOriginalName(),
  215.                 'collection' => $this->getContactMediaCollection(),
  216.             ],
  217.             $userId
  218.         );
  219.     }
  220.     private function getContactMediaCollection(): int
  221.     {
  222.         return $this->collectionManager->getSystemCollection('sulu_contact.contact');
  223.     }
  224. }