Completed
Push — master ( 058e40...9e132c )
by Valentyn
04:01
created

MovieController   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 210
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 28

Test Coverage

Coverage 88.89%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 28
dl 0
loc 210
ccs 64
cts 72
cp 0.8889
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getAll() 0 25 1
A getMovies() 0 14 3
A getMovieReleaseDate() 0 10 2
A postMoviesUpdatePoster() 0 13 2
A getSearch() 0 12 1
A postMovies() 0 19 2
A putMovies() 0 33 1
1
<?php
2
3
namespace App\Movies\Controller;
4
5
use App\Controller\BaseController;
6
use App\Countries\Entity\Country;
7
use App\Filters\FilterBuilder;
8
use App\Filters\Movie as Filter;
9
use App\Movies\DTO\MovieTranslationDTO;
10
use App\Movies\Entity\Movie;
11
use App\Movies\Entity\MovieTranslations;
12
use App\Movies\EventListener\SimilarMoviesProcessor;
13
use App\Movies\Repository\MovieReleaseDateRepository;
14
use App\Movies\Repository\MovieRepository;
15
use App\Movies\Request\CreateMovieRequest;
16
use App\Movies\Request\SearchRequest;
17
use App\Movies\Request\UpdateMovieRequest;
18
use App\Movies\Request\UpdatePosterRequest;
19
use App\Movies\Service\MovieManageService;
20
use App\Movies\Service\SearchService;
21
use App\Movies\Transformer\MovieTransformer;
22
use App\Movies\Utils\Poster;
23
use App\Pagination\CustomPaginatedCollection;
24
use App\Users\Entity\UserRoles;
25
use Enqueue\Client\ProducerInterface;
26
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
27
use Symfony\Component\HttpFoundation\JsonResponse;
28
use Symfony\Component\HttpFoundation\Request;
29
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
30
use Symfony\Component\Routing\Annotation\Route;
31
use Symfony\Component\Validator\Validator\ValidatorInterface;
32
33
/**
34
 * Class MovieController.
35
 */
36
class MovieController extends BaseController
37
{
38
    /**
39
     * Get all movies.
40
     *
41
     * @Route("/api/movies", methods={"GET"})
42
     *
43
     * @param Request         $request
44
     * @param MovieRepository $movieRepository
45
     *
46
     * @throws
47
     *
48
     * @return \Symfony\Component\HttpFoundation\JsonResponse
49
     */
50 34
    public function getAll(Request $request, MovieRepository $movieRepository)
51
    {
52 34
        [$movies, $ids] = $movieRepository->findAllWithIsWatchedFlag($this->getUser(), $this->getGuest());
0 ignored issues
show
Bug introduced by
The variable $movies does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $ids does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
53
54 34
        $offset = (int) $request->get('offset', 0);
55 34
        $limit = $request->get('limit', null);
56
57
        // Its important to keep order of filters from easiest to heaviest in order to improve performance (in theory)
58 34
        $filter = new FilterBuilder(
59 34
            new Filter\YearRange(),
60 34
            new Filter\Rating(),
61 34
            new Filter\Genre(),
62 34
            new Filter\Actor()
63
        );
64
65 34
        $filter->process($request->query, $ids);
66
67
        // todo move this clone qb to CustomPaginatedCollection
68 34
        $count = clone $ids;
69 34
        $count->select('COUNT(m.id)')->resetDQLPart('orderBy');
70
71 34
        $collection = new CustomPaginatedCollection($movies->getQuery(), $ids->getQuery(), $count->getQuery(), $offset, $limit);
72
73 34
        return $this->items($collection, MovieTransformer::list());
74
    }
75
76
    /**
77
     * Get movie resource.
78
     *
79
     * @Route("/api/movies/{id}", methods={"GET"}, requirements={"id"="\d+"})
80
     *
81
     * @param int               $id
82
     * @param MovieRepository   $repository
83
     * @param ProducerInterface $producer
84
     *
85
     * @throws \Doctrine\ORM\NoResultException
86
     * @throws \Doctrine\ORM\NonUniqueResultException
87
     *
88
     * @return JsonResponse
89
     */
90 2
    public function getMovies(int $id, MovieRepository $repository, ProducerInterface $producer)
91
    {
92 2
        if (null === $movie = $repository->findOneForMoviePage($id, $this->getUser())) {
93
            throw new NotFoundHttpException();
94
        }
95
96 2
        if (\count($movie->getSimilarMovies()) === 0) {
97 2
            $producer->sendEvent(SimilarMoviesProcessor::LOAD_SIMILAR_MOVIES, json_encode($movie->getId()));
98
        }
99
100 2
        return $this->response($movie, 200, [], [
101 2
            'groups' => ['view'],
102
        ]);
103
    }
104
105
    /**
106
     * @Route("/api/movies/{movieId}/releaseDate/{countryCode}", methods={"GET"}, requirements={"movieId"="\d+"})
107
     * @ParamConverter("country", options={"mapping": {"countryCode": "code"}})
108
     */
109
    public function getMovieReleaseDate(int $movieId, Country $country, MovieReleaseDateRepository $repository)
110
    {
111
        if (null === $releaseDate = $repository->findOneByCountry($movieId, $country->getId())) {
112
            throw new NotFoundHttpException();
113
        }
114
115
        return $this->response($releaseDate, 200, [], [
116
            'groups' => ['view'],
117
        ]);
118
    }
119
120
    /**
121
     * @Route("/api/movies/{id}/updatePoster", methods={"POST"}, requirements={"id"="\d+"})
122
     *
123
     * @param Movie               $movie
124
     * @param UpdatePosterRequest $request
125
     *
126
     * @return JsonResponse
127
     */
128 1
    public function postMoviesUpdatePoster(Movie $movie, UpdatePosterRequest $request)
129
    {
130 1
        $this->denyAccessUnlessGranted(UserRoles::ROLE_ADMIN);
131
132 1
        if (null === $posterPath = Poster::savePoster($movie->getId(), $request->get('url'))) {
133
            return $this->json([], 400);
134
        }
135
136 1
        $movie->setOriginalPosterUrl(Poster::getUrl($movie->getId()));
137 1
        $this->getDoctrine()->getManager()->flush();
138
139 1
        return $this->json([]);
140
    }
141
142
    /**
143
     * Get movies by title.
144
     *
145
     * @Route("/api/movies/search", methods={"POST"})
146
     *
147
     * @param SearchRequest $request
148
     * @param SearchService $searchService
149
     * @param Request       $currentRequest
150
     *
151
     * @throws \Exception
152
     *
153
     * @return \Symfony\Component\HttpFoundation\JsonResponse
154
     */
155 2
    public function getSearch(SearchRequest $request, SearchService $searchService, Request $currentRequest)
156
    {
157 2
        $offset = (int) $request->get('offset', 0);
158 2
        $limit = $request->get('limit', null);
159
160 2
        $query = $request->get('query');
161 2
        $movies = $searchService->findByQuery($query, $currentRequest->getLocale(), $offset, $limit);
162
163 2
        return $this->response($movies, 200, [], [
164 2
            'groups' => ['list'],
165
        ]);
166
    }
167
168
    /**
169
     * Create new movie.
170
     *
171
     * @Route("/api/movies", methods={"POST"})
172
     *
173
     * @param CreateMovieRequest $request
174
     * @param MovieManageService $service
175
     * @param ValidatorInterface $validator
176
     *
177
     * @throws \Exception
178
     *
179
     * @return \Symfony\Component\HttpFoundation\JsonResponse
180
     */
181 2
    public function postMovies(CreateMovieRequest $request, MovieManageService $service, ValidatorInterface $validator)
182
    {
183 2
        $this->denyAccessUnlessGranted(UserRoles::ROLE_ADMIN);
184
185 1
        $movie = $service->createMovieByRequest($request);
186 1
        $errors = $validator->validate($movie);
187
188 1
        if (\count($errors)) {
189
            return $request->getErrorResponse($errors);
190
        }
191
192 1
        $entityManager = $this->getDoctrine()->getManager();
193 1
        $entityManager->persist($movie);
194 1
        $entityManager->flush();
195
196 1
        return $this->response($movie, 200, [], [
197 1
            'groups' => ['view'],
198
        ]);
199
    }
200
201
    /**
202
     * @Route("/api/movies/{id}", methods={"POST", "PUT", "PATCH"}, requirements={"id"="\d+"})
203
     *
204
     * @param Movie              $movie
205
     * @param UpdateMovieRequest $request
206
     *
207
     * @throws \ErrorException
208
     * @throws \Exception
209
     *
210
     * @return JsonResponse
211
     */
212 2
    public function putMovies(Movie $movie, UpdateMovieRequest $request)
213
    {
214 2
        $this->denyAccessUnlessGranted(UserRoles::ROLE_ADMIN);
215
216 1
        $movieData = $request->get('movie');
217 1
        $movieTranslationsData = $movieData['translations'];
218
219 1
        $movie->setOriginalTitle($movieData['originalTitle']);
220 1
        $movie->setImdbId($movieData['imdbId']);
221 1
        $movie->setRuntime($movieData['runtime']);
222 1
        $movie->setBudget($movieData['budget']);
223 1
        $movie->setReleaseDate(new \DateTimeImmutable($movieData['releaseDate']));
224
225
        $addTranslation = function (array $trans) use ($movie) {
226 1
            $transDto = new MovieTranslationDTO($trans['locale'], $trans['title'], $trans['overview'], null);
227 1
            $movie->addTranslation(
228 1
                new MovieTranslations($movie, $transDto)
229
            );
230 1
        };
231
232
        $updateTranslation = function (array $trans, MovieTranslations $oldTranslation) use ($movie) {
233 1
            $oldTranslation->setTitle($trans['title']);
234 1
            $oldTranslation->setOverview($trans['overview']);
235 1
        };
236
237 1
        $movie->updateTranslations($movieTranslationsData, $addTranslation, $updateTranslation);
238
239 1
        $em = $this->getDoctrine()->getManager();
240 1
        $em->persist($movie); // if there 1+ new translations lets persist movie to be sure that they will be saved
241 1
        $em->flush();
242
243 1
        return new JsonResponse(null, 202);
244
    }
245
}
246