Completed
Push — master ( d5b246...9d25e1 )
by Valentyn
04:39
created

MovieController::getMovieReleaseDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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