zend-blog-3-backend

Форк
0
159 строк · 4.6 Кб
1
<?php
2

3
namespace App\Controller\API;
4

5
use App\API\Transformers\UserTransformer;
6
use App\Controller\BaseController;
7
use App\DTO\ExternalUserDTO;
8
use App\Entity\User;
9
use App\Event\UserEvent;
10
use App\Event\UserExtraEvent;
11
use App\Form\UserFormType;
12
use App\Repository\UserRepository;
13
use App\Service\UserManager;
14
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
15
use Symfony\Component\HttpFoundation\JsonResponse;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\Routing\Annotation\Route;
19
use Symfony\Component\Validator\Validator\ValidatorInterface;
20

21
/**
22
 * @Route("/api/users")
23
 */
24
class UserController extends BaseController
25
{
26
    protected array $errorsPathMap = [
27
        'children[user].children[username].data' => 'username',
28
        'children[user].children[displayName].data' => 'displayName',
29
        'children[user].children[email].data' => 'email',
30
        'username' => 'username',
31
        'email' => 'email',
32
    ];
33

34
    /**
35
     * @Route("", methods={"GET"})
36
     *
37
     * @param Request $request
38
     * @param UserRepository $repository
39
     *
40
     * @return JsonResponse
41
     */
42
    public function findAllAction(Request $request, UserRepository $repository): JsonResponse
43
    {
44
        $pagination = $this->paginate(
45
            $repository->getListQuery(),
46
            $request->query->get('page', 1)
47
        );
48

49
        $result = $this->getDataConverter()
50
            ->getUserArray($pagination);
51

52
        return new JsonResponse($result);
53
    }
54

55
    /**
56
     * @Route("/{id}", requirements={"id": "\d+"}, methods={"GET"})
57
     *
58
     * @param User $entity
59
     *
60
     * @return JsonResponse
61
     */
62
    public function findAction(User $entity): JsonResponse
63
    {
64
        $result = $this->getDataConverter()
65
            ->getUser($entity);
66

67
        return new JsonResponse($result);
68
    }
69

70
    /**
71
     * @Route("/{id}", requirements={"id": "\d+"}, methods={"PUT"})
72
     *
73
     * @param ValidatorInterface $validator
74
     * @param EventDispatcherInterface $dispatcher
75
     * @param Request $request
76
     * @param User $entity
77
     *
78
     * @throws \Psr\Container\ContainerExceptionInterface
79
     * @throws \Psr\Container\NotFoundExceptionInterface
80
     *
81
     * @return JsonResponse
82
     */
83
    public function updateAction(
84
        ValidatorInterface $validator,
85
        EventDispatcherInterface $dispatcher,
86
        Request $request,
87
        User $entity
88
    ): JsonResponse {
89
        $form = $this->createObjectForm('user', UserFormType::class, true);
90
        $form->handleRequest($request);
91

92
        [$formData, $errors] = $this->handleForm($form);
93
        if ($errors) {
94
            return new JsonResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
95
        }
96

97
        UserTransformer::reverseTransform($entity, $formData['user']);
98

99
        $errors = $this->validate($validator, $entity);
100
        if (count($errors) > 0) {
101
            return new JsonResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
102
        }
103

104
        $this->em->persist($entity);
105
        $this->em->flush();
106

107
        $dispatcher->dispatch(new UserEvent($entity));
108

109
        return new JsonResponse($this->getDataConverter()->getUser($entity));
110
    }
111

112
    /**
113
     * @Route("/external", methods={"POST"})
114
     *
115
     * @param ExternalUserDTO $userDTO
116
     * @param UserManager $userManager
117
     * @param ValidatorInterface $validator
118
     * @param EventDispatcherInterface $dispatcher
119
     * @param Request $request
120
     *
121
     * @return JsonResponse
122
     */
123
    public function createExternalAction(
124
        ExternalUserDTO $userDTO,
125
        UserManager $userManager,
126
        ValidatorInterface $validator,
127
        EventDispatcherInterface $dispatcher,
128
        Request $request
129
    ): JsonResponse {
130
        [$user, $foundInfo] = $userManager->findByExternalDTO($userDTO);
131
        if (!$user) {
132
            $user = $userManager->createFromExternalDTO($userDTO);
133

134
            $errors = $this->validate($validator, $user);
135
            if (count($errors) > 0) {
136
                return new JsonResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
137
            }
138

139
            $this->em->persist($user);
140
            $this->em->flush();
141
        }
142

143
        if (!$foundInfo) {
144
            $userInfo = $userManager->saveUserExtraInfo(
145
                $userDTO,
146
                $user,
147
                $request->request->get('ipAddress'),
148
                $request->request->get('userAgent')
149
            );
150

151
            $dispatcher->dispatch(new UserExtraEvent($userInfo));
152
        }
153

154
        return new JsonResponse(
155
            $this->getDataConverter()->getUser($user),
156
            $foundInfo ? Response::HTTP_OK : Response::HTTP_CREATED
157
        );
158
    }
159
}
160

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.