UserSubscriptionRepository   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 295
Duplicated Lines 21.69 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 64
loc 295
rs 9
c 0
b 0
f 0
wmc 35
lcom 1
cbo 4

9 Methods

Rating   Name   Duplication   Size   Complexity  
F getListByCriteria() 4 80 16
B countBy() 0 21 5
A findByUser() 0 10 3
B getExpiringSubscriptionsCount() 29 29 3
B getExpiringSubscriptions() 31 31 3
A getValidSubscriptionsBy() 0 16 1
A checkExistanceInOrder() 0 16 1
A getOrderItemBy() 0 22 1
A findOneBy() 0 15 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * @author Rafał Muszyński <[email protected]>
5
 * @copyright 2014 Sourcefabric o.p.s.
6
 * @license http://www.gnu.org/licenses/gpl-3.0.txt
7
 */
8
namespace Newscoop\PaywallBundle\Entity\Repository;
9
10
use Newscoop\PaywallBundle\Criteria\SubscriptionCriteria;
11
use Newscoop\ListResult;
12
use Newscoop\PaywallBundle\Notifications\Emails;
13
use Newscoop\PaywallBundle\Entity\UserSubscription;
14
15
/**
16
 * Subscription repository.
17
 */
18
class UserSubscriptionRepository extends TranslationRepository
19
{
20
    /**
21
     * Get list for given criteria.
22
     *
23
     * @param SubscriptionCriteria $criteria
24
     *
25
     * @return Newscoop\ListResult
26
     */
27
    public function getListByCriteria(SubscriptionCriteria $criteria, $returnQuery = false, $valid = false)
28
    {
29
        $qb = $this->createQueryBuilder('s');
30
        $list = new ListResult();
31
32
        $qb->select('s', 'p', 'u', 'ss')
33
            ->leftJoin('s.publication', 'p')
34
            ->leftJoin('s.user', 'u')
35
            ->leftJoin('s.subscription', 'ss');
36
37
        if ($criteria->order) {
38
            $qb->where('s.order = :order')
39
                ->setParameter('order', $criteria->order);
40
        }
41
42
        if ($criteria->user) {
43
            $qb->andWhere('s.user = :user')
44
                ->setParameter('user', $criteria->user);
45
        }
46
47
        if ($valid) {
48
            $qb->andWhere($qb->expr()->orX(
49
                $qb->expr()->isNull('s.expire_at'),
50
                $qb->expr()->gt('s.expire_at', '?1')
51
            ))
52
            ->setParameter(1, new \DateTime('now'));
53
        }
54
55
        foreach ($criteria->orderBy as $key => $value) {
56
            switch ($key) {
57
                case '0':
58
                    $qb->orderBy('u.username', $value);
59
                    break;
60
                case '1':
61
                    $qb->orderBy('p.name', $value);
62
                    break;
63
                case '2':
64
                    $qb->orderBy('s.toPay', $value);
65
                    break;
66
                case '3':
67
                    $qb->orderBy('s.currency', $value);
68
                    break;
69
                case '4':
70
                    $qb->orderBy('s.active', $value);
71
                    break;
72
                case '5':
73
                    $qb->orderBy('s.type', $value);
74
                    break;
75
            }
76
        }
77
78 View Code Duplication
        foreach ($criteria->perametersOperators as $key => $operator) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
79
            $qb->andWhere('s.'.$key.' = :'.$key)
80
                ->setParameter($key, $criteria->$key);
81
        }
82
83
        if (!empty($criteria->query)) {
84
            $qb->andWhere($qb->expr()->orX('(u.username LIKE :query)', '(p.name LIKE :query)'));
85
            $qb->setParameter('query', '%'.trim($criteria->query, '%').'%');
86
        }
87
88
        if ($criteria->firstResult != 0) {
89
            $qb->setFirstResult($criteria->firstResult);
90
        }
91
92
        if ($criteria->maxResults != 0) {
93
            $qb->setMaxResults($criteria->maxResults);
94
        }
95
96
        $query = $this->setTranslatableHints($qb->getQuery(), $criteria->locale);
97
        if ($returnQuery) {
98
            return $query;
99
        }
100
101
        $countQb = clone $qb;
102
        $list->count = (int) $countQb->select('COUNT(u)')->getQuery()->getSingleScalarResult();
103
        $list->items = $query->getResult();
104
105
        return $list;
106
    }
107
108
    /**
109
     * Get subscriptions count for given criteria.
110
     *
111
     * @param array $criteria
112
     *
113
     * @return int
114
     */
115
    public function countBy(array $criteria)
116
    {
117
        $queryBuilder = $this->getEntityManager()->createQueryBuilder()
118
            ->select('count(u)')
119
            ->from($this->getEntityName(), 'u');
120
121
        foreach ($criteria as $property => $value) {
122
            if (!is_array($value)) {
123
                $queryBuilder->andWhere("u.$property = :$property");
124
            }
125
        }
126
127
        $query = $queryBuilder->getQuery();
128
        foreach ($criteria as $property => $value) {
129
            if (!is_array($value)) {
130
                $query->setParameter($property, $value);
131
            }
132
        }
133
134
        return (int) $query->getSingleScalarResult();
135
    }
136
137
    /**
138
     * Find by user.
139
     *
140
     * @param Newscoop\Entity\User|int $user
141
     *
142
     * @return array
143
     */
144
    public function findByUser($user)
145
    {
146
        if (empty($user)) {
147
            return array();
148
        }
149
150
        return $this->findBy(array(
151
            'user' => is_numeric($user) ? $user : $user->getId(),
152
        ), array('id' => 'desc'), 1000);
153
    }
154
155
    /**
156
     * Gets expiring subscriptions count.
157
     *
158
     * @param \DateTime $now    Date time
159
     * @param int       $notify Notify type
160
     * @param int       $days   Days amount, when to send notification
161
     *
162
     * @return Doctrine\ORM\Query
163
     */
164 View Code Duplication
    public function getExpiringSubscriptionsCount($now, $notify, $days = 7)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
165
    {
166
        $qb = $this->createQueryBuilder('s');
167
        $qb
168
            ->select('count(s)')
169
            ->where("DATE_SUB(s.expire_at, :days, 'DAY') < :now")
170
            ->andWhere('s.active = :status');
171
172
        switch ($notify) {
173
            case Emails::NOTIFY_LEVEL_ONE:
174
                $qb->andWhere($qb->expr()->isNull('s.notifySentLevelOne'));
175
                break;
176
            case Emails::NOTIFY_LEVEL_TWO:
177
                $qb->andWhere($qb->expr()->isNotNull('s.notifySentLevelOne'));
178
                $qb->andWhere($qb->expr()->isNull('s.notifySentLevelTwo'));
179
                break;
180
            default:
181
                break;
182
        }
183
184
        $qb->setParameters(array(
185
            'status' => 'Y',
186
            'now' => $now,
187
            'days' => $days,
188
        ))
189
        ->orderBy('s.created_at', 'desc');
190
191
        return $qb->getQuery();
192
    }
193
194
    /**
195
     * Gets expiration subscriptions query.
196
     *
197
     * @param int       $offset First result
198
     * @param int       $batch  Max results
199
     * @param \DateTime $now    Date time
200
     * @param int       $notify Notify type
201
     * @param int       $days   Days amount, when to send notification
202
     *
203
     * @return Doctrine\ORM\Query
204
     */
205 View Code Duplication
    public function getExpiringSubscriptions($offset, $batch, $now, $notify, $days = 7)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
    {
207
        $qb = $this->createQueryBuilder('s');
208
        $qb
209
            ->where("DATE_SUB(s.expire_at, :days, 'DAY') < :now")
210
            ->andWhere('s.active = :status');
211
212
        switch ($notify) {
213
            case Emails::NOTIFY_LEVEL_ONE:
214
                $qb->andWhere($qb->expr()->isNull('s.notifySentLevelOne'));
215
                break;
216
            case Emails::NOTIFY_LEVEL_TWO:
217
                $qb->andWhere($qb->expr()->isNotNull('s.notifySentLevelOne'));
218
                $qb->andWhere($qb->expr()->isNull('s.notifySentLevelTwo'));
219
                break;
220
            default:
221
                break;
222
        }
223
224
        $qb
225
            ->setParameters(array(
226
                'status' => 'Y',
227
                'now' => $now,
228
                'days' => $days,
229
            ))
230
            ->orderBy('s.created_at', 'desc')
231
            ->setFirstResult($offset)
232
            ->setMaxResults($batch);
233
234
        return $qb->getQuery();
235
    }
236
237
    public function getValidSubscriptionsBy($userId)
238
    {
239
        $qb = $this->createQueryBuilder('s');
240
241
        $qb
242
            ->select('s', 'ss', 'sp')
243
            ->where('s.user = :user')
244
            ->andWhere("s.active = 'Y'")
245
            ->andWhere('s.expire_at >= :now')
246
            ->join('s.subscription', 'ss')
247
            ->join('ss.specification', 'sp')
248
            ->setParameter('user', $userId)
249
            ->setParameter('now', new \DateTime('now'));
250
251
        return $qb->getQuery();
252
    }
253
254
    /**
255
     * Finds item in order.
256
     */
257
    public function checkExistanceInOrder(UserSubscription $item)
258
    {
259
        $qb = $this
260
            ->createQueryBuilder('i')
261
            ->select('count(i)')
262
            ->where('i.subscription = :subscriptionId')
263
            ->andWhere('i.order = :orderId')
264
            ->setParameters(array(
265
                'subscriptionId' => $item->getSubscription()->getId(),
266
                'orderId' => $item->getOrder()->getId(),
267
            ));
268
269
        return (int) $qb
270
            ->getQuery()->getSingleScalarResult()
271
        ;
272
    }
273
274
    public function getOrderItemBy($id, $user, $period = null)
275
    {
276
        $qb = $this->createQueryBuilder('i');
277
        $query = $qb
278
            ->where('i.user = :user')
279
            ->andWhere('i.subscription = :id')
280
            ->andWhere($qb->expr()->orX(
281
                $qb->expr()->eq('i.active', $qb->expr()->literal('Y')),
282
                $qb->expr()->eq('i.active', $qb->expr()->literal('N'))
283
            ))
284
            ->setParameters(array(
285
                'user' => $user,
286
                'id' => $id,
287
            ))
288
            ->setMaxResults(1)
289
            ->orderBy('i.created_at', 'desc')
290
            ->getQuery();
291
292
        return $query
293
            ->getOneOrNullResult()
294
        ;
295
    }
296
297
    public function findOneBy(array $params, $locale = null)
298
    {
299
        $queryBuilder = $this->createQueryBuilder('i')
300
            ->select('i', 's')
301
            ->leftJoin('i.subscription', 's');
302
303
        foreach ($params as $key => $value) {
304
            $queryBuilder->where('i.'.$key.' = :'.$key);
305
        }
306
307
        $queryBuilder->setParameters($params);
308
        $query = $this->setTranslatableHints($queryBuilder->getQuery(), $locale);
309
310
        return $query->getOneOrNullResult();
311
    }
312
}
313