Completed
Push — master ( 61044a...94728c )
by Rafał
24:26 queued 10:49
created

ArticleRepository   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 281
Duplicated Lines 26.33 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 77.27%

Importance

Changes 0
Metric Value
wmc 53
lcom 1
cbo 11
dl 74
loc 281
rs 6.96
c 0
b 0
f 0
ccs 34
cts 44
cp 0.7727

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 9
 */
31
class ArticleRepository extends EntityRepository implements ArticleRepositoryInterface
32 9
{
33 9
    /**
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 12
        return $this->getQueryByCriteria(new Criteria(), [], 'a')->getQuery()->getResult();
49
    }
50 12
51 12
    /**
52 12
     * {@inheritdoc}
53
     */
54 12
    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 2
            ->leftJoin('m.renditions', 'r')
61
            ->addSelect('m', 'r');
62 2
63 2
        $this->applyCustomFiltering($qb, $criteria);
64 2
65 2
        return $qb;
66
    }
67 2
68
    /**
69 2
     * {@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 7
76
        if (null !== $status) {
77 7
            $queryBuilder
78 7
                ->where('a.status = :status')
79 7
                ->setParameter('status', $criteria->get('status', $status));
80
        }
81 7
82 2
        $this->applyCustomFiltering($queryBuilder, $criteria);
83 2
        $this->applyCriteria($queryBuilder, $criteria, 'a');
84 2
85
        return (int) $queryBuilder->getQuery()->getSingleScalarResult();
86
    }
87 2
88
    /**
89
     * {@inheritdoc}
90 7
     */
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 7
        $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 7
            return [];
103 3
        }
104 3
105 3
        $ids = [];
106
107
        foreach ($selectedArticles as $partialArticle) {
108 3
            $ids[] = $partialArticle['a_id'];
109
        }
110
        $articlesQueryBuilder->addSelect('a')
111 7
            ->leftJoin('a.media', 'm')
112 7
            ->leftJoin('m.renditions', 'r')
113 7
            ->addSelect('m', 'r')
114
            ->andWhere('a.id IN (:ids)')
115 7
            ->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
    private function applyCustomFiltering(QueryBuilder $queryBuilder, Criteria $criteria)
159
    {
160
        foreach (['metadata', 'extra', 'exclude_metadata', 'exclude_extra'] as $name) {
161
            if (!$criteria->has($name)) {
162
                continue;
163
            }
164
165
            if (!is_array($criteria->get($name))) {
166
                $criteria->remove($name);
167
168
                continue;
169
            }
170
171
            $orX = $queryBuilder->expr()->orX();
172
            foreach ($criteria->get($name) as $key => $value) {
173
                $search = ('***' !== $value) ? [$key => $value] : $key;
174
                if ('metadata' === $name || 'exclude_metadata' === $name) {
175
                    $valueExpression = \str_replace('{', '',
176
                        \str_replace('}', '',
177
                            '%'.\json_encode($search).'%'
178
                        )
179
                    );
180
                } else {
181
                    $valueExpression = '%'.\str_replace('a:1:{', '',
182
                        \str_replace(';}', ';',
183
                            \serialize($search).'%'
184
                        )
185
                    );
186
                }
187
188
                $valueExpression = $queryBuilder->expr()->literal($valueExpression);
189
                if (false === strpos($name, 'exclude_')) {
190
                    $orX->add($queryBuilder->expr()->like('a.'.$name, $valueExpression));
191
                } else {
192
                    $orX->add($queryBuilder->expr()->notLike('a.'.\str_replace('exclude_', '', $name), $valueExpression));
193
                }
194
            }
195
196
            $queryBuilder->andWhere($orX);
197
            $criteria->remove($name);
198
        }
199
200
        if ($criteria->has('keywords')) {
201
            $queryBuilder->leftJoin('a.keywords', 'k');
202
            $orX = $queryBuilder->expr()->orX();
203
            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...
204
                $queryBuilder->setParameter($key, $value);
205
                $orX->add($queryBuilder->expr()->eq('k.name', '?'.$key));
206
                $orX->add($queryBuilder->expr()->eq('k.slug', '?'.$key));
207
            }
208
209
            $queryBuilder->andWhere($orX);
210
            $criteria->remove('keywords');
211
        }
212
213 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...
214
            $publishedBefore = $criteria->get('publishedBefore');
215
            $queryBuilder->andWhere('a.publishedAt < :before')
216
                ->setParameter('before', $publishedBefore instanceof \DateTimeInterface ? $publishedBefore : new \DateTime($publishedBefore));
217
            $criteria->remove('publishedBefore');
218
        }
219
220 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...
221
            $publishedAfter = $criteria->get('publishedAfter');
222
            $queryBuilder->andWhere('a.publishedAt > :after')
223
                ->setParameter('after', $publishedAfter instanceof \DateTimeInterface ? $publishedAfter : new \DateTime($publishedAfter));
224
            $criteria->remove('publishedAfter');
225
        }
226
227
        if ($criteria->has('query') && strlen($query = trim($criteria->get('query'))) > 0) {
228
            $like = $queryBuilder->expr()->like('a.title', $queryBuilder->expr()->literal('%'.$query.'%'));
229
230
            $queryBuilder->andWhere($like);
231
            $criteria->remove('query');
232
        }
233
234 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...
235
            $articleSourcesQueryBuilder = $this->getEntityManager()
236
                ->createQueryBuilder()
237
                ->select('excluded_article.id')
238
                ->from(ArticleSourceReference::class, 'excluded_asr')
239
                ->join('excluded_asr.article', 'excluded_article')
240
                ->join('excluded_asr.articleSource', 'excluded_articleSource');
241
242
            $orX = $queryBuilder->expr()->orX();
243
            foreach ((array) $criteria->get('exclude_source') as $value) {
244
                $orX->add($articleSourcesQueryBuilder->expr()->eq('excluded_articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
245
            }
246
            $articleSourcesQueryBuilder->andWhere($orX);
247
            $queryBuilder->andWhere($queryBuilder->expr()->notIn('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
248
249
            $criteria->remove('exclude_source');
250
        }
251
252 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...
253
            $articleSourcesQueryBuilder = $this->getEntityManager()
254
                ->createQueryBuilder()
255
                ->select('article.id')
256
                ->from(ArticleSourceReference::class, 'asr')
257
                ->join('asr.article', 'article')
258
                ->join('asr.articleSource', 'articleSource');
259
            $orX = $queryBuilder->expr()->orX();
260
            foreach ((array) $criteria->get('source') as $value) {
261
                $orX->add($articleSourcesQueryBuilder->expr()->eq('articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
262
            }
263
            $articleSourcesQueryBuilder->andWhere($orX);
264
            $queryBuilder->andWhere($queryBuilder->expr()->in('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
265
266
            $criteria->remove('source');
267
        }
268
269
        if (
270
            ($criteria->has('author') && !empty($criteria->get('author'))) ||
271
            ($criteria->has('exclude_author') && !empty($criteria->get('exclude_author')))
272
        ) {
273
            $queryBuilder->leftJoin('a.authors', 'au');
274
        }
275
276 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...
277
            $orX = $queryBuilder->expr()->orX();
278
            foreach ((array) $criteria->get('author') as $value) {
279
                $orX->add($queryBuilder->expr()->eq('au.name', $queryBuilder->expr()->literal($value)));
280
            }
281
282
            $queryBuilder->andWhere($orX);
283
            $criteria->remove('author');
284
        }
285
286 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...
287
            $andX = $queryBuilder->expr()->andX();
288
            foreach ((array) $criteria->get('exclude_author') as $value) {
289
                $andX->add($queryBuilder->expr()->neq('au.name', $queryBuilder->expr()->literal($value)));
290
            }
291
292
            $queryBuilder->andWhere($andX);
293
            $criteria->remove('exclude_author');
294
        }
295
296
        if ($criteria->has('exclude_article') && !empty($criteria->get('exclude_article'))) {
297
            $excludedArticles = [];
298
            foreach ((array) $criteria->get('exclude_article') as $value) {
299
                if (is_numeric($value)) {
300
                    $excludedArticles[] = $value;
301
                } elseif ($value instanceof Meta and $value->getValues() instanceof ArticleInterface) {
302
                    $excludedArticles[] = $value->getValues()->getId();
303
                }
304
            }
305
306
            $queryBuilder->andWhere('a.id NOT IN (:excludedArticles)')
307
                ->setParameter('excludedArticles', $excludedArticles);
308
            $criteria->remove('exclude_article');
309
        }
310
    }
311
}
312