src/Controller/Api/ClubController.php line 100

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Api;
  3. use App\Entity\Club;
  4. use Hateoas\HateoasBuilder;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use OpenApi\Annotations as OA;
  10. use Psr\Log\LoggerInterface;
  11. use App\Model\ClubCreate;
  12. use App\Service\ClubService;
  13. use App\Util\RequestUtil;
  14. use App\Exception\ViolationException;
  15. use Symfony\Component\Serializer\SerializerInterface;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use App\Model\ClubView;
  18. use App\Util\StringUtils;
  19. use App\Entity\Events;
  20. use App\Model\ClubUpdate;
  21. use App\Security\Roles;
  22. use App\Entity\EntityFinder;
  23. use App\Exception\CRMException;
  24. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  25. use Doctrine\Persistence\ManagerRegistry;
  26. class ClubController extends AbstractController
  27. {
  28.     private LoggerInterface $logger;
  29.     
  30.     public function __construct(LoggerInterface $logger)
  31.     {
  32.         $this->logger $logger;
  33.     }
  34.    
  35.     /**
  36.      * @Route("/api/club", name="api_club_list-active", methods={"GET"})
  37.      * @OA\Get(
  38.      *     operationId="getActiveClubList",
  39.      *     tags={"Club"},
  40.      *     path="/api/club",
  41.      *     summary="List all active clubs",
  42.      *     @OA\Response(
  43.      *         response="200",
  44.      *         description="Successful",
  45.      *         @OA\MediaType(
  46.      *             mediaType="application/hal+json",
  47.      *             @OA\Schema(
  48.      *                 type="array",
  49.      *                 @OA\Items(ref="#/components/schemas/Club")
  50.      *             )
  51.      *         )
  52.      *     )
  53.      * )
  54.      */
  55.     public function listActive()
  56.     {
  57.         $clubService = new ClubService($this->container->get('doctrine'));
  58.         $clubViews $clubService->convertAllActiveToView();
  59.         $hateoas HateoasBuilder::create()->build();
  60.         return new Response(
  61.             $hateoas->serialize($clubViews'json'),
  62.             Response::HTTP_OK,
  63.             array('Content-Type' => 'application/hal+json'));
  64.     }
  65.     /**
  66.      * @Route("/api/club/{uuid}", name="api_get_club", methods={"GET"}, requirements={"uuid"="[a-z0-9_]{2,64}"})
  67.      * @OA\Get(
  68.      *     operationId="getClub",
  69.      *     tags={"Club"},
  70.      *     path="/api/club/{uuid}",
  71.      *     summary="Give a club",
  72.      *     @OA\Parameter(
  73.      *         description="UUID of club",
  74.      *         in="path",
  75.      *         name="uuid",
  76.      *         required=true,
  77.      *         @OA\Schema(
  78.      *             format="string",
  79.      *             type="string",
  80.      *             pattern="[a-z0-9_]{2,64}"
  81.      *         )
  82.      *     ),
  83.      *     @OA\Response(
  84.      *         response="200",
  85.      *         description="Successful",
  86.      *         @OA\MediaType(
  87.      *             mediaType="application/hal+json",
  88.      *             @OA\Schema(ref="#/components/schemas/Club")
  89.      *         )
  90.      *     ),
  91.      *     @OA\Response(response="404", description="Club not found", @OA\MediaType(mediaType="application/hal+json", @OA\Schema(ref="#/components/schemas/Error")))
  92.      * )
  93.      */
  94.     public function one($uuid)
  95.     {
  96.         $entityFinder = new EntityFinder($this->container->get('doctrine'));
  97.         /** @var Club $club */
  98.         $club $entityFinder->findOneByOrThrow(Club::class, ['uuid' => $uuid]); // 404
  99.         
  100.         $clubService = new ClubService($this->container->get('doctrine'));
  101.         $clubView $clubService->convertToView($club);
  102.         
  103.         $hateoas HateoasBuilder::create()->build();
  104.         return new Response(
  105.             $hateoas->serialize($clubView'json'),
  106.             Response::HTTP_OK,
  107.             array('Content-Type' => 'application/hal+json'));
  108.     }
  109.     /**
  110.      * @Route("/api/club", name="api_club_create", methods={"POST"}, requirements={"uuid"="[a-z0-9_]{2,64}"})
  111.      * @OA\Post(
  112.      *     operationId="createClub",
  113.      *     tags={"Club"},
  114.      *     path="/api/club",
  115.      *     summary="Create a club",
  116.      *     security = {{"basicAuth": {}}},
  117.      *     @OA\Parameter(name="X-ClientId", in="header",  required=true, example="my-client-name", @OA\Schema(format="string", type="string", pattern="[a-z0-9_]{2,64}")),
  118.      *     @OA\RequestBody(
  119.      *         description="User object that needs to be added",
  120.      *         required=true,
  121.      *         @OA\JsonContent(ref="#/components/schemas/ClubCreate"),
  122.      *     ),
  123.      *     @OA\Response(
  124.      *         response="201",
  125.      *         description="Successful",
  126.      *         @OA\MediaType(
  127.      *             mediaType="application/hal+json",
  128.      *             @OA\Schema(ref="#/components/schemas/Club")
  129.      *         )
  130.      *     ),
  131.      *     @OA\Response(response="400", description="Request contains not valid field", @OA\MediaType(mediaType="application/hal+json", @OA\Schema(ref="#/components/schemas/Error"))),
  132.      *     @OA\Response(response="403", description="Forbidden to create a club", @OA\MediaType(mediaType="application/hal+json", @OA\Schema(ref="#/components/schemas/Error")))
  133.      * )
  134.      */
  135.     public function create(Request $requestSerializerInterface $serializerTranslatorInterface $translator)
  136.     {
  137.         $this->denyAccessUnlessGranted(Roles::ROLE_ADMIN); // 403
  138.         
  139.         $requestUtil = new RequestUtil($serializer$translator);
  140.         /** @var ClubCreate $clubToCreate */
  141.         $clubToCreate $requestUtil->validate($requestClubCreate::class); // 400
  142.         
  143.         $name $clubToCreate->getName();
  144.         $uuid $clubToCreate->getUuid();
  145.         if($uuid == null || trim($uuid) === '') {
  146.             $uuid StringUtils::nameToUuid($name);
  147.         }
  148.         
  149.         /** @var ManagerRegistry $doctrine */
  150.         $doctrine $this->container->get('doctrine');
  151.         
  152.         $entityFinder = new EntityFinder($doctrine);
  153.         $entityFinder->findNoneByOrThrow(Club::class, ['uuid' => $uuid],
  154.             function() use($uuid) {
  155.                 throw new CRMException(Response::HTTP_BAD_REQUEST'UUID already used: '.$uuid); // 400
  156.             });
  157.         
  158.         $club = new Club();
  159.         $club->setActive($clubToCreate->isActive());
  160.         $club->setUuid($uuid);
  161.         $club->setName($name);
  162.         $club->setLogo('default.png');
  163.         $club->setContactEmails($clubToCreate->getContactEmails());
  164.         $club->setContactPhone($clubToCreate->getContactPhone());
  165.         $club->setPriceCenacleJoining($clubToCreate->getPriceCenacleJoining());
  166.         $club->setPriceBaseSubscribe($clubToCreate->getPriceBaseSubscribe());
  167.         $club->setFacebookUrl($clubToCreate->getFacebookUrl());
  168.         $club->setInstagramUrl($clubToCreate->getInstagramUrl());
  169.         $club->setMailingList($clubToCreate->getMailingList());
  170.         $club->setTwitterUrl($clubToCreate->getTwitterUrl());
  171.         $club->setWebsiteUrl($clubToCreate->getWebsiteUrl());
  172.         $doctrine->getManager()->persist($club);
  173.         
  174.         $data = ['name' => $name'uuid' => $uuid'active' => $clubToCreate->isActive()];
  175.         Events::add($doctrineEvents::CLUB_CREATED$this->getUser(), $request$data);
  176.         $this->logger->debug('Club created: '.json_encode($data));
  177.         $hateoas HateoasBuilder::create()->build();
  178.         return new Response(
  179.             $hateoas->serialize(new ClubView($clubnullnull), 'json'),
  180.             Response::HTTP_CREATED// 201
  181.             array('Content-Type' => 'application/hal+json'));
  182.     }
  183.     /**
  184.      * @Route("/api/club/{uuid}", name="api_club_update", methods={"PATCH"}, requirements={"uuid"="[a-z0-9_]{2,64}"})
  185.      * @OA\Patch(
  186.      *     operationId="updateClub",
  187.      *     tags={"Club"},
  188.      *     path="/api/club/{uuid}",
  189.      *     summary="Update a club",
  190.      *     security = {{"basicAuth": {}}},
  191.      *     @OA\Parameter(name="X-ClientId", in="header", required=true, example="my-client-name", @OA\Schema(format="string", type="string", pattern="[a-z0-9_]{2,64}")),
  192.      *     @OA\Parameter(
  193.      *         description="UUID of club",
  194.      *         in="path",
  195.      *         name="uuid",
  196.      *         required=true,
  197.      *         @OA\Schema(
  198.      *             format="string",
  199.      *             type="string",
  200.      *             pattern="[a-z0-9_]{2,64}"
  201.      *         )
  202.      *     ),
  203.      *     @OA\RequestBody(
  204.      *         description="User object that needs to be added",
  205.      *         required=true,
  206.      *         @OA\JsonContent(ref="#/components/schemas/ClubUpdate"),
  207.      *     ),
  208.      *     @OA\Response(response="204", description="Successful"),
  209.      *     @OA\Response(response="400", description="Request contains not valid field", @OA\MediaType(mediaType="application/hal+json", @OA\Schema(ref="#/components/schemas/Error"))),
  210.      *     @OA\Response(response="403", description="Forbidden to update a club", @OA\MediaType(mediaType="application/hal+json", @OA\Schema(ref="#/components/schemas/Error"))),
  211.      *     @OA\Response(response="404", description="Club not found", @OA\MediaType(mediaType="application/hal+json", @OA\Schema(ref="#/components/schemas/Error")))
  212.      * )
  213.      */
  214.     public function update(Request $request$uuidSerializerInterface $serializerTranslatorInterface $translatorSessionInterface $session)
  215.     {
  216.         $this->denyAccessUnlessGranted(Roles::ROLE_ADMIN); // 403
  217.         
  218.         $requestUtil = new RequestUtil($serializer$translator);
  219.         /** @var ClubUpdate $clubToUpdate */
  220.         $clubToUpdate $requestUtil->validate($requestClubUpdate::class); // 400
  221.         $this->logger->debug('Club update.priceCenacleJoining: '.$clubToUpdate->getPriceCenacleJoining());
  222.         $this->logger->debug('Club update.priceBaseSubscribe: '.$clubToUpdate->getPriceBaseSubscribe());
  223.         
  224.         $doctrine $this->container->get('doctrine');
  225.         
  226.         $entityFinder = new EntityFinder($doctrine);
  227.         /** @var Club $club */
  228.         $club $entityFinder->findOneByOrThrow(Club::class, ['uuid' => $uuid]); // 404
  229.         
  230.         $newuuid $clubToUpdate->getUuid();
  231.         if( ! empty($newuuid) && $newuuid !== $club->getUuid()) {
  232.             $entityFinder->findNoneByOrThrow(Club::class, ['uuid' => $newuuid],
  233.                 function() use($newuuid) {
  234.                     throw new CRMException(Response::HTTP_BAD_REQUEST'UUID already used: '.$newuuid); // 400
  235.                 });
  236.         }
  237.         
  238.         $entityUpdater = new EntityUpdater($doctrine$request$this->getUser(), Events::CLUB_UPDATED$this->logger);
  239.         $entityUpdater->update('active'$clubToUpdate->isActive(), $club->getActive(), function($v) use($club) { $club->setActive($v); });
  240.         //$entityUpdater->update('uuid', $newuuid, $club->getUuid(), function($v) use($club) { $club->setUuid($v); });
  241.         $entityUpdater->update('name'$clubToUpdate->getName(), $club->getName(), function($v) use($club) { $club->setName($v); });
  242.         $entityUpdater->update('contactemails'$clubToUpdate->getContactEmails(), $club->getContactEmails(), function($v) use($club) { $club->setContactEmails($v); });
  243.         $entityUpdater->update('contactphone'$clubToUpdate->getContactPhone(), $club->getContactPhone(), function($v) use($club) { $club->setContactPhone($v); });
  244.         $entityUpdater->update('pricecenaclejoining'$clubToUpdate->getPriceCenacleJoining(), $club->getPriceCenacleJoining(),
  245.             function($v) use($club) { $club->setPriceCenacleJoining($v); },
  246.             function($v) use($club) { $club->setPriceCenacleJoining(null); });
  247.         $entityUpdater->update('pricebasesubscribe'$clubToUpdate->getPriceBaseSubscribe(), $club->getPriceBaseSubscribe(),
  248.             function($v) use($club) { $club->setPriceBaseSubscribe($v); },
  249.             function($v) use($club) { $club->setPriceBaseSubscribe(null); });
  250.         $entityUpdater->update('facebookurl'$clubToUpdate->getFacebookUrl(), $club->getFacebookUrl(), function($v) use($club) { $club->setFacebookUrl($v); });
  251.         $entityUpdater->update('instagramurl'$clubToUpdate->getInstagramUrl(), $club->getInstagramUrl(), function($v) use($club) { $club->setInstagramUrl($v); });
  252.         $entityUpdater->update('mailinglist'$clubToUpdate->getMailingList(), $club->getMailingList(), function($v) use($club) { $club->setMailingList($v); });
  253.         $entityUpdater->update('twitterurl'$clubToUpdate->getTwitterUrl(), $club->getTwitterUrl(), function($v) use($club) { $club->setTwitterUrl($v); });
  254.         $entityUpdater->update('websiteurl'$clubToUpdate->getWebsiteUrl(), $club->getWebsiteUrl(), function($v) use($club) { $club->setWebsiteUrl($v); });
  255.         $updatedResponse $entityUpdater->toResponse($club'Club updated', ['id' => $club->getId()]);
  256.         
  257.         $this->logger->debug('Club.priceCenacleJoining: '.$club->getPriceCenacleJoining());
  258.         $this->logger->debug('Club.priceBaseSubscribe: '.$club->getPriceBaseSubscribe());
  259.         
  260.         $selectedClub $session->get('club-selected');
  261.         if($selectedClub !== null && $selectedClub->uuid === $uuid) {
  262.             $u $newuuid !== null $newuuid $uuid;
  263.             $clubResponse $this->forward('App\Controller\Api\ClubController::one', ['uuid' => $u]);
  264.             $session->set('club-selected'json_decode($clubResponse->getContent()));
  265.         }
  266.         
  267.         return $updatedResponse;
  268.     }
  269. }