Completed
Push — master ( 72d332...2291c9 )
by Valentyn
12:18
created

MovieController::getMovies()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.7085

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 4
cts 7
cp 0.5714
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 3
crap 3.7085
1
<?php
2
3
namespace App\Movies\Controller;
4
5
use App\Controller\BaseController;
6
use App\Countries\Entity\Country;
7
use App\Movies\DTO\MovieTranslationDTO;
8
use App\Movies\Entity\Movie;
9
use App\Movies\Entity\MovieTranslations;
10
use App\Movies\EventListener\SimilarMoviesProcessor;
11
use App\Movies\Repository\MovieReleaseDateRepository;
12
use App\Movies\Repository\MovieRepository;
13
use App\Movies\Request\CreateMovieRequest;
14
use App\Movies\Request\SearchRequest;
15
use App\Movies\Request\UpdateMovieRequest;
16
use App\Movies\Request\UpdatePosterRequest;
17
use App\Movies\Service\MovieManageService;
18
use App\Movies\Service\SearchService;
19
use App\Movies\Transformer\MovieTransformer;
20
use App\Movies\Utils\Poster;
21
use App\Pagination\CustomPaginatedCollection;
22
use App\Users\Entity\UserRoles;
23
use Enqueue\Client\ProducerInterface;
24
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
25
use Symfony\Component\HttpFoundation\JsonResponse;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
28
use Symfony\Component\Routing\Annotation\Route;
29
use Symfony\Component\Validator\Validator\ValidatorInterface;
30
31
/**
32
 * Class MovieController.
33
 */
34
class MovieController extends BaseController
35
{
36
    /**
37
     * Get all movies.
38
     *
39
     * @Route("/api/movies", methods={"GET"})
40
     *
41
     * @param Request         $request
42
     * @param MovieRepository $movieRepository
43
     *
44
     * @return \Symfony\Component\HttpFoundation\JsonResponse
45
     */
46 17
    public function getAll(Request $request, MovieRepository $movieRepository)
47
    {
48 17
        [$movies, $ids, $count] = $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...
Bug introduced by
The variable $count 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...
49
50 17
        $offset = (int) $request->get('offset', 0);
51 17
        $limit = $request->get('limit', null);
52
53 17
        $collection = new CustomPaginatedCollection($movies, $ids, $count, $offset, $limit);
54
55 17
        return $this->items($collection, MovieTransformer::list());
56
    }
57
58
    /**
59
     * Get movie resource.
60
     *
61
     * @Route("/api/movies/{id}", methods={"GET"}, requirements={"id"="\d+"})
62
     *
63
     * @param int               $id
64
     * @param MovieRepository   $repository
65
     * @param ProducerInterface $producer
66
     *
67
     * @throws \Doctrine\ORM\NoResultException
68
     * @throws \Doctrine\ORM\NonUniqueResultException
69
     *
70
     * @return JsonResponse
71
     */
72 2
    public function getMovies(int $id, MovieRepository $repository, ProducerInterface $producer)
73
    {
74 2
        if (null === $movie = $repository->findOneForMoviePage($id, $this->getUser())) {
75
            throw new NotFoundHttpException();
76
        }
77
78 2
        if (\count($movie->getSimilarMovies()) === 0) {
79 2
            $producer->sendEvent(SimilarMoviesProcessor::LOAD_SIMILAR_MOVIES, json_encode($movie->getId()));
80
        }
81
82
        return $this->response($movie, 200, [], [
83
            'groups' => ['view'],
84
        ]);
85
    }
86
87
    /**
88
     * @Route("/api/movies/{movieId}/releaseDate/{countryCode}", methods={"GET"}, requirements={"movieId"="\d+"})
89
     * @ParamConverter("country", options={"mapping": {"countryCode": "code"}})
90
     */
91
    public function getMovieReleaseDate(int $movieId, Country $country, MovieReleaseDateRepository $repository)
92
    {
93
        if (null === $releaseDate = $repository->findOneByCountry($movieId, $country->getId())) {
94
            throw new NotFoundHttpException();
95
        }
96
97
        return $this->response($releaseDate, 200, [], [
98
            'groups' => ['view'],
99
        ]);
100
    }
101
102
    /**
103
     * @Route("/api/movies/{id}/updatePoster", methods={"POST"}, requirements={"id"="\d+"})
104
     *
105
     * @param Movie               $movie
106
     * @param UpdatePosterRequest $request
107
     *
108
     * @return JsonResponse
109
     */
110 1
    public function postMoviesUpdatePoster(Movie $movie, UpdatePosterRequest $request)
111
    {
112 1
        $this->denyAccessUnlessGranted(UserRoles::ROLE_ADMIN);
113
114 1
        if (null === $posterPath = Poster::savePoster($movie->getId(), $request->get('url'))) {
115
            return $this->json([], 400);
116
        }
117
118 1
        $movie->setOriginalPosterUrl(Poster::getUrl($movie->getId()));
119 1
        $this->getDoctrine()->getManager()->flush();
120
121 1
        return $this->json([]);
122
    }
123
124
    /**
125
     * Get movies by title.
126
     *
127
     * @Route("/api/movies/search", methods={"POST"})
128
     *
129
     * @param SearchRequest $request
130
     * @param SearchService $searchService
131
     * @param Request       $currentRequest
132
     *
133
     * @throws \Exception
134
     *
135
     * @return \Symfony\Component\HttpFoundation\JsonResponse
136
     */
137 2
    public function getSearch(SearchRequest $request, SearchService $searchService, Request $currentRequest)
138
    {
139 2
        $offset = (int) $request->get('offset', 0);
140 2
        $limit = $request->get('limit', null);
141
142 2
        $query = $request->get('query');
143 2
        $movies = $searchService->findByQuery($query, $currentRequest->getLocale(), $offset, $limit);
144
145 1
        return $this->response($movies, 200, [], [
146 1
            'groups' => ['list'],
147
        ]);
148
    }
149
150
    /**
151
     * Create new movie.
152
     *
153
     * @Route("/api/movies", methods={"POST"})
154
     *
155
     * @param CreateMovieRequest $request
156
     * @param MovieManageService $service
157
     * @param ValidatorInterface $validator
158
     *
159
     * @throws \Exception
160
     *
161
     * @return \Symfony\Component\HttpFoundation\JsonResponse
162
     */
163 2
    public function postMovies(CreateMovieRequest $request, MovieManageService $service, ValidatorInterface $validator)
164
    {
165 2
        $this->denyAccessUnlessGranted(UserRoles::ROLE_ADMIN);
166
167 1
        $movie = $service->createMovieByRequest($request);
168 1
        $errors = $validator->validate($movie);
169
170 1
        if (\count($errors)) {
171
            return $request->getErrorResponse($errors);
172
        }
173
174 1
        $entityManager = $this->getDoctrine()->getManager();
175 1
        $entityManager->persist($movie);
176 1
        $entityManager->flush();
177
178 1
        return $this->response($movie, 200, [], [
179 1
            'groups' => ['view'],
180
        ]);
181
    }
182
183
    /**
184
     * @Route("/api/movies/{id}", methods={"POST", "PUT", "PATCH"}, requirements={"id"="\d+"})
185
     *
186
     * @param Movie              $movie
187
     * @param UpdateMovieRequest $request
188
     *
189
     * @throws \ErrorException
190
     * @throws \Exception
191
     *
192
     * @return JsonResponse
193
     */
194 2
    public function putMovies(Movie $movie, UpdateMovieRequest $request)
195
    {
196 2
        $this->denyAccessUnlessGranted(UserRoles::ROLE_ADMIN);
197
198 1
        $movieData = $request->get('movie');
199 1
        $movieTranslationsData = $movieData['translations'];
200
201 1
        $movie->setOriginalTitle($movieData['originalTitle']);
202 1
        $movie->setImdbId($movieData['imdbId']);
203 1
        $movie->setRuntime($movieData['runtime']);
204 1
        $movie->setBudget($movieData['budget']);
205 1
        $movie->setReleaseDate(new \DateTimeImmutable($movieData['releaseDate']));
206
207
        $addTranslation = function (array $trans) use ($movie) {
208 1
            $transDto = new MovieTranslationDTO($trans['locale'], $trans['title'], $trans['overview'], null);
209 1
            $movie->addTranslation(
210 1
                new MovieTranslations($movie, $transDto)
211
            );
212 1
        };
213
214
        $updateTranslation = function (array $trans, MovieTranslations $oldTranslation) use ($movie) {
215 1
            $oldTranslation->setTitle($trans['title']);
216 1
            $oldTranslation->setOverview($trans['overview']);
217 1
        };
218
219 1
        $movie->updateTranslations($movieTranslationsData, $addTranslation, $updateTranslation);
220
221 1
        $em = $this->getDoctrine()->getManager();
222 1
        $em->persist($movie); // if there 1+ new translations lets persist movie to be sure that they will be saved
223 1
        $em->flush();
224
225 1
        return new JsonResponse(null, 202);
226
    }
227
}
228