Completed
Push — master ( 9f52f6...71d672 )
by Valentyn
04:42
created

MovieRepository::findAllIdsByTmdbIds()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 8
cp 0
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Movies\Repository;
6
7
use App\Guests\Entity\GuestSession;
8
use App\Movies\Entity\Movie;
9
use App\Users\Entity\User;
10
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
11
use Doctrine\ORM\Query;
12
use Doctrine\ORM\QueryBuilder;
13
use Symfony\Bridge\Doctrine\RegistryInterface;
14
15
/**
16
 * @method Movie|null find($id, $lockMode = null, $lockVersion = null)
17
 * @method Movie|null findOneBy(array $criteria, array $orderBy = null)
18
 * @method Movie[]    findAll()
19
 * @method Movie[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
20
 */
21
class MovieRepository extends ServiceEntityRepository
22
{
23 16
    public function __construct(RegistryInterface $registry)
24
    {
25 16
        parent::__construct($registry, Movie::class);
26 16
    }
27
28 12
    private function getBaseQuery(): QueryBuilder
29
    {
30 12
        return $this->createQueryBuilder('m')
31 12
            ->leftJoin('m.translations', 'mt')
32 12
            ->addSelect('mt')
33 12
            ->leftJoin('m.genres', 'mg')
34 12
            ->addSelect('mg')
35 12
            ->leftJoin('mg.translations', 'mgt')
36 12
            ->addSelect('mgt');
37
    }
38
39
    /**
40
     * @param int       $id
41
     * @param User|null $user
42
     *
43
     * @throws \Doctrine\ORM\NoResultException
44
     * @throws \Doctrine\ORM\NonUniqueResultException
45
     *
46
     * @return Movie|null
47
     */
48 1
    public function findOneForMoviePage(int $id, ?User $user = null): ?Movie
49
    {
50 1
        if ($user === null) {
51 1
            return $this->getBaseQuery()
52 1
                ->where('m.id = :id')
53 1
                ->setParameter('id', $id)
54 1
                ->getQuery()
55 1
                ->getSingleResult();
56
        }
57
58
        $result = $this->getBaseQuery()
59
            ->where('m.id = :id')
60
            ->leftJoin('m.userWatchedMovie', 'uwm', 'WITH', 'uwm.user = :user_id')
61
            ->addSelect('uwm')
62
            ->leftJoin('m.userRecommendedMovie', 'urm', 'WITH', 'urm.user = :user_id AND urm.originalMovie = :id')
63
            ->addSelect('urm')
64
            ->setParameter('user_id', $user->getId())
65
            ->setParameter('id', $id)
66
            ->getQuery()
67
            ->getSingleResult();
68
69
        return $result;
70
    }
71
72
    public function findAllByIdsWithFlags(array $ids, int $userId)
73
    {
74
        $result = $this->getBaseQuery()
75
            ->leftJoin('m.userWatchedMovie', 'uwm', 'WITH', 'uwm.user = :user_id') // if this relation exists then user has already watched this movie
76
            ->addSelect('uwm')
77
            ->leftJoin('m.userRecommendedMovie', 'urm', 'WITH', 'urm.user = :user_id AND urm.originalMovie IN (:ids)')
78
            ->addSelect('urm')
79
            ->where('m.id IN (:ids)')
80
            ->setParameter('user_id', $userId)
81
            ->setParameter('ids', $ids)
82
            ->getQuery()
83
            ->getResult();
84
85
        // Sorting here because ORDER BY FIELD(m.id, ...$ids) not working in postgres, we need to use joins on sorted table and so on, but I dont want to
86
        // todo => add sorting to sql
87
        $reversedIds = array_flip($ids);
88
        usort($result, function (Movie $movie1, Movie $movie2) use ($reversedIds) {
89
            return $reversedIds[$movie1->getId()] <=> $reversedIds[$movie2->getId()];
90
        });
91
92
        return $result;
93
    }
94
95
    public function findAllByIdsWithoutFlags(array $ids)
96
    {
97
        $result = $this->findAllByIds($ids);
98
99
        // Sorting here because ORDER BY FIELD(m.id, ...$ids) not working in postgres, we need to use joins on sorted table and so on, but I dont want to
100
        // todo => add sorting to sql
101
        $reversedIds = array_flip($ids);
102
        usort($result, function (Movie $movie1, Movie $movie2) use ($reversedIds) {
103
            return $reversedIds[$movie1->getId()] <=> $reversedIds[$movie2->getId()];
104
        });
105
106
        return $result;
107
    }
108
109
    public function findAllWithIsUserWatchedFlag(User $user)
110
    {
111
        $result = $this->getBaseQuery()
112
            ->leftJoin('m.userWatchedMovie', 'uwm', 'WITH', 'uwm.user = :user_id') // if this relation exists then user has already watched this movie
113
            ->addSelect('uwm')
114
            ->setParameter('user_id', $user->getId())
115
            ->orderBy('m.id', 'DESC')
116
            ->getQuery();
117
118
        return $result;
119
    }
120
121 8
    public function findAllWithIsGuestWatchedFlag(?GuestSession $guestSession)
122
    {
123 8
        $guestSessionId = $guestSession ? $guestSession->getId() : 0;
124
125 8
        $result = $this->getBaseQuery()
126 8
            ->leftJoin('m.guestWatchedMovie', 'gwm', 'WITH', 'gwm.guestSession = :guest_session_id') // if this relation exists then guest has already watched this movie
127 8
            ->addSelect('gwm')
128 8
            ->setParameter('guest_session_id', $guestSessionId)
129 8
            ->orderBy('m.id', 'DESC')
130 8
            ->getQuery();
131
132 8
        return $result;
133
    }
134
135
    /**
136
     * @param array $ids
137
     *
138
     * @return array|Movie[]
139
     */
140
    public function findAllByIds(array $ids)
141
    {
142
        $result = $this->getBaseQuery()
143
            ->where('m.id IN (:ids)')
144
            ->setParameter('ids', $ids)
145
            ->getQuery()
146
            ->getResult();
147
148
        return $result;
149
    }
150
151
    /**
152
     * @param array $ids
153
     *
154
     * @return array|Movie[]
155
     */
156
    public function findAllByIdsWithSimilarMovies(array $ids): array
157
    {
158
        $result = $this->createQueryBuilder('m')
159
            ->leftJoin('m.similarMovies', 'sm')
160
            ->addSelect('sm')
161
            ->where('m.id IN (:ids)')
162
            ->setParameter('ids', $ids)
163
            ->getQuery()
164
            ->getScalarResult();
165
166
        return $result;
167
    }
168
169
    /**
170
     * @param array $ids
171
     *
172
     * @return array|Movie[]
173
     */
174 1
    public function findAllByTmdbIds(array $ids)
175
    {
176 1
        $result = $this->getBaseQuery()
177 1
            ->where('m.tmdb.id IN (:ids)')
178 1
            ->setParameter('ids', $ids)
179 1
            ->getQuery()
180 1
            ->getResult();
181
182 1
        return $result;
183
    }
184
185
    /**
186
     * @param array $ids
187
     *
188
     * @return array of int
189
     */
190
    public function findAllIdsByTmdbIds(array $ids)
191
    {
192
        $result = $this->createQueryBuilder('m')
193
            ->select('m.id, m.tmdb.voteAverage')
194
            ->where('m.tmdb.id IN (:ids)')
195
            ->setParameter('ids', $ids)
196
            ->getQuery()
197
            ->getScalarResult();
198
199
        return $result;
200
    }
201
202 2
    public function getAllWatchedMoviesByUserId(int $userId): Query
203
    {
204 2
        $result = $this->getBaseQuery()
205 2
            ->leftJoin('m.userWatchedMovie', 'uwm', 'WITH', 'uwm.user = :user_id')
206 2
            ->addSelect('uwm')
207 2
            ->setParameter('user_id', $userId)
208 2
            ->andWhere('uwm.id != 0')
209 2
            ->orderBy('uwm.id', 'DESC')
210 2
            ->getQuery();
211
212 2
        return $result;
213
    }
214
215
    public function findAllQuery()
216
    {
217
        $result = $this->getBaseQuery()
218
            ->orderBy('m.id', 'DESC')
219
            ->getQuery();
220
221
        return $result;
222
    }
223
224 2
    public function findByTitleQuery(string $query)
225
    {
226 2
        $query = mb_strtolower($query);
227 2
        $result = $this->getBaseQuery()
228 2
            ->andWhere('LOWER(m.originalTitle) LIKE :title OR LOWER(mt.title) LIKE :title')
229 2
            ->setParameter('title', "%{$query}%")
230 2
            ->getQuery();
231
232 2
        return $result;
233
    }
234
235 7
    public function findOneByIdOrTmdbId(?int $id = null, ?int $tmdb_id = null)
236
    {
237 7
        if ($id === null && $tmdb_id === null) {
238
            throw new \InvalidArgumentException('Movie ID or TMDB ID should be provided');
239
        }
240
241 7
        return $id ? $this->find($id) : $this->findOneBy(['tmdb.id' => $tmdb_id]);
242
    }
243
}
244