Completed
Pull Request — 2.1 (#1080)
by Paweł
09:58
created

ArticleRepository   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 289
Duplicated Lines 22.49 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
dl 65
loc 289
c 0
b 0
f 0
wmc 55
lcom 1
cbo 11
rs 6

10 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 getArticlesByBodyContent() 0 8 1
A getPaginatedByCriteria() 11 11 2
A getQueryForRouteArticles() 0 4 1
F applyCustomFiltering() 54 157 42

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\Doctrine\ArticleRepositoryInterface;
21
use SWP\Bundle\ContentBundle\Model\ArticleAuthorReference;
22
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
23
use SWP\Bundle\ContentBundle\Model\ArticleSourceReference;
24
use SWP\Bundle\StorageBundle\Doctrine\ORM\EntityRepository;
25
use SWP\Component\Common\Criteria\Criteria;
26
use SWP\Component\Common\Pagination\PaginationData;
27
use SWP\Component\TemplatesSystem\Gimme\Meta\Meta;
28
29
/**
30
 * Class ArticleRepository.
31
 */
32
class ArticleRepository extends EntityRepository implements ArticleRepositoryInterface
33
{
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function findOneBySlug($slug)
38
    {
39
        return $this->findOneBy([
40
            'slug' => $slug,
41
        ]);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function findAllArticles()
48
    {
49
        return $this->getQueryByCriteria(new Criteria(), [], 'a')->getQuery()->getResult();
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getByCriteria(Criteria $criteria, array $sorting): QueryBuilder
56
    {
57
        $qb = $this->getQueryByCriteria($criteria, $sorting, 'a');
58
        $qb->andWhere('a.status = :status')
59
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED))
60
            ->leftJoin('a.media', 'm')
61
            ->leftJoin('m.renditions', 'r')
62
            ->addSelect('m', 'r');
63
64
        $this->applyCustomFiltering($qb, $criteria);
65
66
        return $qb;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function countByCriteria(Criteria $criteria, $status = ArticleInterface::STATUS_PUBLISHED): int
73
    {
74
        $queryBuilder = $this->createQueryBuilder('a')
75
            ->select('COUNT(a.id)');
76
77
        if (null !== $status) {
78
            $queryBuilder
79
                ->where('a.status = :status')
80
                ->setParameter('status', $criteria->get('status', $status));
81
        }
82
83
        $this->applyCustomFiltering($queryBuilder, $criteria);
84
        $this->applyCriteria($queryBuilder, $criteria, 'a');
85
86
        return (int) $queryBuilder->getQuery()->getSingleScalarResult();
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function getArticlesByCriteria(Criteria $criteria, array $sorting = []): QueryBuilder
93
    {
94
        $queryBuilder = $this->getArticlesByCriteriaIds($criteria);
95
        $queryBuilder->andWhere('a.route IS NOT NULL');
96
        $this->applyCustomFiltering($queryBuilder, $criteria);
97
        $this->applyCriteria($queryBuilder, $criteria, 'a');
98
        $this->applySorting($queryBuilder, $sorting, 'a', $criteria);
99
        $articlesQueryBuilder = clone $queryBuilder;
100
        $this->applyLimiting($queryBuilder, $criteria);
101
        $selectedArticles = $queryBuilder->getQuery()->getScalarResult();
102
        if (!is_array($selectedArticles)) {
103
            return [];
104
        }
105
106
        $ids = [];
107
108
        foreach ($selectedArticles as $partialArticle) {
109
            $ids[] = $partialArticle['a_id'];
110
        }
111
        $articlesQueryBuilder->addSelect('a')
112
            ->leftJoin('a.media', 'm')
113
            ->leftJoin('m.renditions', 'r')
114
            ->addSelect('m', 'r')
115
            ->andWhere('a.id IN (:ids)')
116
            ->setParameter('ids', $ids);
117
118
        return $articlesQueryBuilder;
119
    }
120
121
    public function getArticlesByCriteriaIds(Criteria $criteria): QueryBuilder
122
    {
123
        $queryBuilder = $this->createQueryBuilder('a')
124
            ->select('partial a.{id}')
125
            ->where('a.status = :status')
126
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED));
127
128
        return $queryBuilder;
129
    }
130
131
    public function getArticlesByBodyContent(string $content): array
132
    {
133
        $queryBuilder = $this->createQueryBuilder('a');
134
        $like = $queryBuilder->expr()->like('a.body', $queryBuilder->expr()->literal('%'.$content.'%'));
135
        $queryBuilder->andWhere($like);
136
137
        return $queryBuilder->getQuery()->getResult();
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 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...
144
    {
145
        $queryBuilder = $this->getQueryByCriteria($criteria, $sorting, 'a');
146
        $this->applyCustomFiltering($queryBuilder, $criteria);
147
148
        if (null === $paginationData) {
149
            $paginationData = new PaginationData();
150
        }
151
152
        return $this->getPaginator($queryBuilder, $paginationData);
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function getQueryForRouteArticles(string $identifier, array $order = [])
159
    {
160
        throw new \Exception('Not implemented');
161
    }
162
163
    private function applyCustomFiltering(QueryBuilder $queryBuilder, Criteria $criteria)
164
    {
165
        foreach (['metadata', 'extra', 'exclude_metadata', 'exclude_extra'] as $name) {
166
            if (!$criteria->has($name)) {
167
                continue;
168
            }
169
170
            if (!is_array($criteria->get($name))) {
171
                $criteria->remove($name);
172
173
                continue;
174
            }
175
176
            $orX = $queryBuilder->expr()->orX();
177
            foreach ($criteria->get($name) as $key => $value) {
178
                $search = ('***' !== $value) ? [$key => $value] : $key;
179
                if ('metadata' === $name || 'exclude_metadata' === $name) {
180
                    $valueExpression = '%'.\rtrim(\ltrim(\json_encode($search), '{'), '}').'%';
181
                } else {
182
                    $valueExpression = '%'.\rtrim(\ltrim(\serialize($search), 'a:1:{'), ';}').'%';
183
                }
184
185
                $valueExpression = $queryBuilder->expr()->literal($valueExpression);
186
                if (false === strpos($name, 'exclude_')) {
187
                    $orX->add($queryBuilder->expr()->like('a.'.$name, $valueExpression));
188
                } else {
189
                    $orX->add($queryBuilder->expr()->notLike('a.'.\str_replace('exclude_', '', $name), $valueExpression));
190
                }
191
            }
192
            $queryBuilder->andWhere($orX);
193
            $criteria->remove($name);
194
        }
195
196
        if ($criteria->has('keywords')) {
197
            $queryBuilder->leftJoin('a.keywords', 'k');
198
            $orX = $queryBuilder->expr()->orX();
199
            foreach ($criteria->get('keywords') as $key => $value) {
200
                $queryBuilder->setParameter($key, $value);
201
                $orX->add($queryBuilder->expr()->eq('k.name', '?'.$key));
202
                $orX->add($queryBuilder->expr()->eq('k.slug', '?'.$key));
203
            }
204
205
            $queryBuilder->andWhere($orX);
206
            $criteria->remove('keywords');
207
        }
208
209 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...
210
            $publishedBefore = $criteria->get('publishedBefore');
211
            $queryBuilder->andWhere('a.publishedAt < :before')
212
                ->setParameter('before', $publishedBefore instanceof \DateTimeInterface ? $publishedBefore : new \DateTime($publishedBefore));
213
            $criteria->remove('publishedBefore');
214
        }
215
216 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...
217
            $publishedAfter = $criteria->get('publishedAfter');
218
            $queryBuilder->andWhere('a.publishedAt > :after')
219
                ->setParameter('after', $publishedAfter instanceof \DateTimeInterface ? $publishedAfter : new \DateTime($publishedAfter));
220
            $criteria->remove('publishedAfter');
221
        }
222
223
        if ($criteria->has('query') && strlen($query = trim($criteria->get('query'))) > 0) {
224
            $like = $queryBuilder->expr()->like('a.title', $queryBuilder->expr()->literal('%'.$query.'%'));
225
226
            $queryBuilder->andWhere($like);
227
            $criteria->remove('query');
228
        }
229
230 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...
231
            $articleSourcesQueryBuilder = $this->getEntityManager()
232
                ->createQueryBuilder()
233
                ->select('excluded_article.id')
234
                ->from(ArticleSourceReference::class, 'excluded_asr')
235
                ->join('excluded_asr.article', 'excluded_article')
236
                ->join('excluded_asr.articleSource', 'excluded_articleSource');
237
238
            $orX = $queryBuilder->expr()->orX();
239
            foreach ((array) $criteria->get('exclude_source') as $value) {
240
                $orX->add($articleSourcesQueryBuilder->expr()->eq('excluded_articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
241
            }
242
            $articleSourcesQueryBuilder->andWhere($orX);
243
            $queryBuilder->andWhere($queryBuilder->expr()->notIn('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
244
245
            $criteria->remove('exclude_source');
246
        }
247
248 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...
249
            $articleSourcesQueryBuilder = $this->getEntityManager()
250
                ->createQueryBuilder()
251
                ->select('article.id')
252
                ->from(ArticleSourceReference::class, 'asr')
253
                ->join('asr.article', 'article')
254
                ->join('asr.articleSource', 'articleSource');
255
            $orX = $queryBuilder->expr()->orX();
256
            foreach ((array) $criteria->get('source') as $value) {
257
                $orX->add($articleSourcesQueryBuilder->expr()->eq('articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
258
            }
259
            $articleSourcesQueryBuilder->andWhere($orX);
260
            $queryBuilder->andWhere($queryBuilder->expr()->in('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
261
262
            $criteria->remove('source');
263
        }
264
265
        if (
266
            ($criteria->has('author') && !empty($criteria->get('author'))) ||
267
            ($criteria->has('exclude_author') && !empty($criteria->get('exclude_author')))
268
        ) {
269
            $queryBuilder->leftJoin('a.authors', 'au');
270
        }
271
272 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...
273
            $orX = $queryBuilder->expr()->orX();
274
            foreach ((array) $criteria->get('author') as $value) {
275
                $orX->add($queryBuilder->expr()->eq('au.name', $queryBuilder->expr()->literal($value)));
276
            }
277
278
            $queryBuilder->andWhere($orX);
279
            $criteria->remove('author');
280
        }
281
282
        if ($criteria->has('exclude_author') && !empty($criteria->get('exclude_author'))) {
283
            $excludedAuthors = $this->getEntityManager()
284
                ->createQueryBuilder()
285
                ->from(ArticleAuthorReference::class, 'article_author')
286
                ->select('aa.id')
287
                ->join('article_author.author', 'aaa')
288
                ->join('article_author.article', 'aa')
289
                ->where('aaa.name IN (:authors)');
290
291
            $queryBuilder->setParameter('authors', array_values((array) $criteria->get('exclude_author')));
292
            $queryBuilder->andWhere($queryBuilder->expr()->not($queryBuilder->expr()->in('a.id', $excludedAuthors->getQuery()->getDQL())));
293
294
            $criteria->remove('exclude_author');
295
        }
296
297
        if ($criteria->has('exclude_article') && !empty($criteria->get('exclude_article'))) {
298
            $excludedArticles = [];
299
            foreach ((array) $criteria->get('exclude_article') as $value) {
300
                if (is_numeric($value)) {
301
                    $excludedArticles[] = $value;
302
                } elseif ($value instanceof Meta and $value->getValues() instanceof ArticleInterface) {
303
                    $excludedArticles[] = $value->getValues()->getId();
304
                }
305
            }
306
307
            $queryBuilder->andWhere('a.id NOT IN (:excludedArticles)')
308
                ->setParameter('excludedArticles', $excludedArticles);
309
            $criteria->remove('exclude_article');
310
        }
311
312
        if ($criteria->has('exclude_route') && !empty($criteria->get('exclude_route'))) {
313
            $andX = $queryBuilder->expr()->andX();
314
            $andX->add($queryBuilder->expr()->notIn('a.route', (array) $criteria->get('exclude_route')));
315
            $queryBuilder->andWhere($andX);
316
317
            $criteria->remove('exclude_route');
318
        }
319
    }
320
}
321