Completed
Push — 1.5 ( b0c0ab...c3fc8e )
by Rafał
10:00
created

ArticleRepository   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 285
Duplicated Lines 25.96 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 53
lcom 1
cbo 11
dl 74
loc 285
rs 6.96
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A findOneBySlug() 0 6 1
A findAllArticles() 0 4 1
A getByCriteria() 0 13 1
A countByCriteria() 0 16 2
A getArticlesByCriteria() 0 28 3
A getArticlesByCriteriaIds() 0 9 1
A getPaginatedByCriteria() 11 11 2
A getQueryForRouteArticles() 0 4 1
F applyCustomFiltering() 63 153 41

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ArticleRepository often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ArticleRepository, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Content Bundle.
7
 *
8
 * Copyright 2016 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2016 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\ContentBundle\Doctrine\ORM;
18
19
use Doctrine\ORM\QueryBuilder;
20
use SWP\Bundle\ContentBundle\Model\ArticleSourceReference;
21
use SWP\Component\Common\Criteria\Criteria;
22
use SWP\Bundle\ContentBundle\Doctrine\ArticleRepositoryInterface;
23
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
24
use SWP\Bundle\StorageBundle\Doctrine\ORM\EntityRepository;
25
use SWP\Component\Common\Pagination\PaginationData;
26
use SWP\Component\TemplatesSystem\Gimme\Meta\Meta;
27
28
/**
29
 * Class ArticleRepository.
30
 */
31
class ArticleRepository extends EntityRepository implements ArticleRepositoryInterface
32
{
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function findOneBySlug($slug)
37
    {
38
        return $this->findOneBy([
39
            'slug' => $slug,
40
        ]);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function findAllArticles()
47
    {
48
        return $this->getQueryByCriteria(new Criteria(), [], 'a')->getQuery()->getResult();
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function getByCriteria(Criteria $criteria, array $sorting): QueryBuilder
55
    {
56
        $qb = $this->getQueryByCriteria($criteria, $sorting, 'a');
57
        $qb->andWhere('a.status = :status')
58
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED))
59
            ->leftJoin('a.media', 'm')
60
            ->leftJoin('m.renditions', 'r')
61
            ->addSelect('m', 'r');
62
63
        $this->applyCustomFiltering($qb, $criteria);
64
65
        return $qb;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function countByCriteria(Criteria $criteria, $status = ArticleInterface::STATUS_PUBLISHED): int
72
    {
73
        $queryBuilder = $this->createQueryBuilder('a')
74
            ->select('COUNT(a.id)');
75
76
        if (null !== $status) {
77
            $queryBuilder
78
                ->where('a.status = :status')
79
                ->setParameter('status', $criteria->get('status', $status));
80
        }
81
82
        $this->applyCustomFiltering($queryBuilder, $criteria);
83
        $this->applyCriteria($queryBuilder, $criteria, 'a');
84
85
        return (int) $queryBuilder->getQuery()->getSingleScalarResult();
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function getArticlesByCriteria(Criteria $criteria, array $sorting = []): QueryBuilder
92
    {
93
        $queryBuilder = $this->getArticlesByCriteriaIds($criteria);
94
        $queryBuilder->andWhere('a.route IS NOT NULL');
95
        $this->applyCustomFiltering($queryBuilder, $criteria);
96
        $this->applyCriteria($queryBuilder, $criteria, 'a');
97
        $this->applySorting($queryBuilder, $sorting, 'a', $criteria);
98
        $articlesQueryBuilder = clone $queryBuilder;
99
        $this->applyLimiting($queryBuilder, $criteria);
100
        $selectedArticles = $queryBuilder->getQuery()->getScalarResult();
101
        if (!is_array($selectedArticles)) {
102
            return [];
103
        }
104
105
        $ids = [];
106
107
        foreach ($selectedArticles as $partialArticle) {
108
            $ids[] = $partialArticle['a_id'];
109
        }
110
        $articlesQueryBuilder->addSelect('a')
111
            ->leftJoin('a.media', 'm')
112
            ->leftJoin('m.renditions', 'r')
113
            ->addSelect('m', 'r')
114
            ->andWhere('a.id IN (:ids)')
115
            ->setParameter('ids', $ids);
116
117
        return $articlesQueryBuilder;
118
    }
119
120
    /**
121
     * @param Criteria $criteria
122
     *
123
     * @return QueryBuilder
124
     */
125
    public function getArticlesByCriteriaIds(Criteria $criteria): QueryBuilder
126
    {
127
        $queryBuilder = $this->createQueryBuilder('a')
128
            ->select('partial a.{id}')
129
            ->where('a.status = :status')
130
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED));
131
132
        return $queryBuilder;
133
    }
134
135
    /**
136
     * {@inheritdoc}
137
     */
138 View Code Duplication
    public function getPaginatedByCriteria(Criteria $criteria, array $sorting = [], PaginationData $paginationData = null)
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...
139
    {
140
        $queryBuilder = $this->getQueryByCriteria($criteria, $sorting, 'a');
141
        $this->applyCustomFiltering($queryBuilder, $criteria);
142
143
        if (null === $paginationData) {
144
            $paginationData = new PaginationData();
145
        }
146
147
        return $this->getPaginator($queryBuilder, $paginationData);
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public function getQueryForRouteArticles(string $identifier, array $order = [])
154
    {
155
        throw new \Exception('Not implemented');
156
    }
157
158
    /**
159
     * @param QueryBuilder $queryBuilder
160
     * @param Criteria     $criteria
161
     */
162
    private function applyCustomFiltering(QueryBuilder $queryBuilder, Criteria $criteria)
163
    {
164
        foreach (['metadata', 'extra', 'exclude_metadata', 'exclude_extra'] as $name) {
165
            if (!$criteria->has($name)) {
166
                continue;
167
            }
168
169
            if (!is_array($criteria->get($name))) {
170
                $criteria->remove($name);
171
172
                continue;
173
            }
174
175
            $orX = $queryBuilder->expr()->orX();
176
            foreach ($criteria->get($name) as $key => $value) {
177
                $search = ('***' !== $value) ? [$key => $value] : $key;
178
                if ('metadata' === $name || 'exclude_metadata' === $name) {
179
                    $valueExpression = \str_replace('{', '',
180
                        \str_replace('}', '',
181
                            '%'.\json_encode($search).'%'
182
                        )
183
                    );
184
                } else {
185
                    $valueExpression = '%'.\str_replace('a:1:{', '',
186
                        \str_replace(';}', ';',
187
                            \serialize($search).'%'
188
                        )
189
                    );
190
                }
191
192
                $valueExpression = $queryBuilder->expr()->literal($valueExpression);
193
                if (false === strpos($name, 'exclude_')) {
194
                    $orX->add($queryBuilder->expr()->like('a.'.$name, $valueExpression));
195
                } else {
196
                    $orX->add($queryBuilder->expr()->notLike('a.'.\str_replace('exclude_', '', $name), $valueExpression));
197
                }
198
            }
199
200
            $queryBuilder->andWhere($orX);
201
            $criteria->remove($name);
202
        }
203
204
        if ($criteria->has('keywords')) {
205
            $queryBuilder->leftJoin('a.keywords', 'k');
206
            $orX = $queryBuilder->expr()->orX();
207
            foreach ($criteria->get('keywords') as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $criteria->get('keywords') of type object|integer|double|string|null|boolean|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
208
                $queryBuilder->setParameter($key, $value);
209
                $orX->add($queryBuilder->expr()->eq('k.name', '?'.$key));
210
                $orX->add($queryBuilder->expr()->eq('k.slug', '?'.$key));
211
            }
212
213
            $queryBuilder->andWhere($orX);
214
            $criteria->remove('keywords');
215
        }
216
217 View Code Duplication
        if ($criteria->has('publishedBefore') && null !== $criteria->get('publishedBefore')) {
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...
218
            $publishedBefore = $criteria->get('publishedBefore');
219
            $queryBuilder->andWhere('a.publishedAt < :before')
220
                ->setParameter('before', $publishedBefore instanceof \DateTimeInterface ? $publishedBefore : new \DateTime($publishedBefore));
221
            $criteria->remove('publishedBefore');
222
        }
223
224 View Code Duplication
        if ($criteria->has('publishedAfter') && null !== $criteria->get('publishedAfter')) {
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...
225
            $publishedAfter = $criteria->get('publishedAfter');
226
            $queryBuilder->andWhere('a.publishedAt > :after')
227
                ->setParameter('after', $publishedAfter instanceof \DateTimeInterface ? $publishedAfter : new \DateTime($publishedAfter));
228
            $criteria->remove('publishedAfter');
229
        }
230
231
        if ($criteria->has('query') && strlen($query = trim($criteria->get('query'))) > 0) {
232
            $like = $queryBuilder->expr()->like('a.title', $queryBuilder->expr()->literal('%'.$query.'%'));
233
234
            $queryBuilder->andWhere($like);
235
            $criteria->remove('query');
236
        }
237
238 View Code Duplication
        if ($criteria->has('exclude_source') && !empty($criteria->get('exclude_source'))) {
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...
239
            $articleSourcesQueryBuilder = $this->getEntityManager()
240
                ->createQueryBuilder()
241
                ->select('excluded_article.id')
242
                ->from(ArticleSourceReference::class, 'excluded_asr')
243
                ->join('excluded_asr.article', 'excluded_article')
244
                ->join('excluded_asr.articleSource', 'excluded_articleSource');
245
246
            $orX = $queryBuilder->expr()->orX();
247
            foreach ((array) $criteria->get('exclude_source') as $value) {
248
                $orX->add($articleSourcesQueryBuilder->expr()->eq('excluded_articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
249
            }
250
            $articleSourcesQueryBuilder->andWhere($orX);
251
            $queryBuilder->andWhere($queryBuilder->expr()->notIn('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
252
253
            $criteria->remove('exclude_source');
254
        }
255
256 View Code Duplication
        if ($criteria->has('source') && !empty($criteria->get('source'))) {
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...
257
            $articleSourcesQueryBuilder = $this->getEntityManager()
258
                ->createQueryBuilder()
259
                ->select('article.id')
260
                ->from(ArticleSourceReference::class, 'asr')
261
                ->join('asr.article', 'article')
262
                ->join('asr.articleSource', 'articleSource');
263
            $orX = $queryBuilder->expr()->orX();
264
            foreach ((array) $criteria->get('source') as $value) {
265
                $orX->add($articleSourcesQueryBuilder->expr()->eq('articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
266
            }
267
            $articleSourcesQueryBuilder->andWhere($orX);
268
            $queryBuilder->andWhere($queryBuilder->expr()->in('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
269
270
            $criteria->remove('source');
271
        }
272
273
        if (
274
            ($criteria->has('author') && !empty($criteria->get('author'))) ||
275
            ($criteria->has('exclude_author') && !empty($criteria->get('exclude_author')))
276
        ) {
277
            $queryBuilder->leftJoin('a.authors', 'au');
278
        }
279
280 View Code Duplication
        if ($criteria->has('author') && !empty($criteria->get('author'))) {
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...
281
            $orX = $queryBuilder->expr()->orX();
282
            foreach ((array) $criteria->get('author') as $value) {
283
                $orX->add($queryBuilder->expr()->eq('au.name', $queryBuilder->expr()->literal($value)));
284
            }
285
286
            $queryBuilder->andWhere($orX);
287
            $criteria->remove('author');
288
        }
289
290 View Code Duplication
        if ($criteria->has('exclude_author') && !empty($criteria->get('exclude_author'))) {
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...
291
            $andX = $queryBuilder->expr()->andX();
292
            foreach ((array) $criteria->get('exclude_author') as $value) {
293
                $andX->add($queryBuilder->expr()->neq('au.name', $queryBuilder->expr()->literal($value)));
294
            }
295
296
            $queryBuilder->andWhere($andX);
297
            $criteria->remove('exclude_author');
298
        }
299
300
        if ($criteria->has('exclude_article') && !empty($criteria->get('exclude_article'))) {
301
            $excludedArticles = [];
302
            foreach ((array) $criteria->get('exclude_article') as $value) {
303
                if (is_numeric($value)) {
304
                    $excludedArticles[] = $value;
305
                } elseif ($value instanceof Meta and $value->getValues() instanceof ArticleInterface) {
306
                    $excludedArticles[] = $value->getValues()->getId();
307
                }
308
            }
309
310
            $queryBuilder->andWhere('a.id NOT IN (:excludedArticles)')
311
                ->setParameter('excludedArticles', $excludedArticles);
312
            $criteria->remove('exclude_article');
313
        }
314
    }
315
}
316