Completed
Push — master ( 4da1f4...8b580e )
by Paweł
08:27
created

ArticleRepository::getPaginatedByCriteria()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 0
cp 0
cc 2
eloc 9
nc 2
nop 3
crap 6
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 Elastica\Query;
21
use SWP\Bundle\ContentBundle\Model\ArticleSourceReference;
22
use SWP\Component\Common\Criteria\Criteria;
23
use SWP\Bundle\ContentBundle\Doctrine\ArticleRepositoryInterface;
24
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
25
use SWP\Bundle\StorageBundle\Doctrine\ORM\EntityRepository;
26
use SWP\Component\Common\Pagination\PaginationData;
27
28
/**
29
 * Class ArticleRepository.
30 8
 */
31
class ArticleRepository extends EntityRepository implements ArticleRepositoryInterface
32 8
{
33 8
    /**
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
            ->leftJoin('a.sources', 's')
62 2
            ->leftJoin('a.authors', 'au')
63 2
            ->addSelect('m', 's', 'r', 'au');
64 2
65 2
        $this->applyCustomFiltering($qb, $criteria);
66
67 2
        return $qb;
68
    }
69 2
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function countByCriteria(Criteria $criteria, $status = ArticleInterface::STATUS_PUBLISHED): int
74
    {
75 5
        $queryBuilder = $this->createQueryBuilder('a')
76
            ->select('COUNT(a.id)')
77 5
            ->leftJoin('a.authors', 'au');
78 5
79 5
        if (null !== $status) {
80
            $queryBuilder
81 5
                ->where('a.status = :status')
82 2
                ->setParameter('status', $criteria->get('status', $status));
83 2
        }
84 2
85
        $this->applyCustomFiltering($queryBuilder, $criteria);
86
        $this->applyCriteria($queryBuilder, $criteria, 'a');
87 2
88
        return (int) $queryBuilder->getQuery()->getSingleScalarResult();
89
    }
90 5
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function getArticlesByCriteria(Criteria $criteria, array $sorting = []): QueryBuilder
95
    {
96 5
        $queryBuilder = $this->getArticlesByCriteriaIds($criteria);
97
        $queryBuilder->addSelect('au');
98
        $queryBuilder->leftJoin('a.authors', 'au');
99
        $this->applyCustomFiltering($queryBuilder, $criteria);
100
        $this->applyCriteria($queryBuilder, $criteria, 'a');
101
        $this->applySorting($queryBuilder, $sorting, 'a');
102 5
        $articlesQueryBuilder = clone $queryBuilder;
103 3
        $this->applyLimiting($queryBuilder, $criteria);
104 3
        $selectedArticles = $queryBuilder->getQuery()->getScalarResult();
105 3
106
        if (!is_array($selectedArticles)) {
107
            return [];
108 3
        }
109
110
        $ids = [];
111 5
112 5
        foreach ($selectedArticles as $partialArticle) {
113 5
            $ids[] = $partialArticle['a_id'];
114
        }
115 5
        $articlesQueryBuilder->addSelect('a')
116
            ->leftJoin('a.media', 'm')
117
            ->leftJoin('m.renditions', 'r')
118
            ->leftJoin('a.sources', 's')
119
            ->addSelect('m', 'r', 's')
120
            ->andWhere('a.id IN (:ids)')
121
            ->setParameter('ids', $ids);
122
123
        return $articlesQueryBuilder;
124
    }
125
126
    /**
127
     * @param Criteria $criteria
128
     *
129
     * @return QueryBuilder
130
     */
131
    public function getArticlesByCriteriaIds(Criteria $criteria): QueryBuilder
132
    {
133
        $queryBuilder = $this->createQueryBuilder('a')
134
            ->select('partial a.{id}')
135
            ->where('a.status = :status')
136
            ->setParameter('status', $criteria->get('status', ArticleInterface::STATUS_PUBLISHED));
137
138
        return $queryBuilder;
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function getPaginatedByCriteria(Criteria $criteria, array $sorting = [], PaginationData $paginationData = null)
145
    {
146
        $queryBuilder = $this->getQueryByCriteria($criteria, $sorting, 'a');
147
        $queryBuilder
148
            ->addSelect('au')
149
            ->leftJoin('a.authors', 'au');
150
151
        $this->applyCustomFiltering($queryBuilder, $criteria);
152
153
        if (null === $paginationData) {
154
            $paginationData = new PaginationData();
155
        }
156
157
        return $this->getPaginator($queryBuilder, $paginationData);
158
    }
159
160
    /**
161
     * {@inheritdoc}
162
     */
163
    public function getQueryForRouteArticles(string $identifier, array $order = [])
164
    {
165
        throw new \Exception('Not implemented');
166
    }
167
168
    /**
169
     * @param QueryBuilder $queryBuilder
170
     * @param Criteria     $criteria
171
     */
172
    private function applyCustomFiltering(QueryBuilder $queryBuilder, Criteria $criteria)
173
    {
174
        foreach (['metadata'] as $name) {
175
            if (!$criteria->has($name)) {
176
                continue;
177
            }
178
179
            if (!is_array($criteria->get($name))) {
180
                $criteria->remove($name);
181
182
                continue;
183
            }
184
185
            $orX = $queryBuilder->expr()->orX();
186 View Code Duplication
            foreach ($criteria->get($name) as $value) {
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...
187
                $valueExpression = $queryBuilder->expr()->literal('%'.$value.'%');
188
                $orX->add($queryBuilder->expr()->like('a.metadata', $valueExpression));
189
            }
190
191
            $queryBuilder->andWhere($orX);
192
            $criteria->remove($name);
193
        }
194
195
        if ($criteria->has('keywords')) {
196
            $orX = $queryBuilder->expr()->orX();
197 View Code Duplication
            foreach ($criteria->get('keywords') as $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...
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...
198
                $valueExpression = $queryBuilder->expr()->literal('%'.$value.'%');
199
                $orX->add($queryBuilder->expr()->like('a.keywords', $valueExpression));
200
            }
201
202
            $queryBuilder->andWhere($orX);
203
            $criteria->remove('keywords');
204
        }
205
206 View Code Duplication
        if ($criteria->has('publishedBefore') && $criteria->get('publishedBefore') instanceof \DateTime) {
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...
207
            $queryBuilder->andWhere('a.publishedAt < :before')
208
                ->setParameter('before', $criteria->get('publishedBefore'));
209
            $criteria->remove('publishedBefore');
210
        }
211
212 View Code Duplication
        if ($criteria->has('publishedAfter') && $criteria->get('publishedAfter') instanceof \DateTime) {
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...
213
            $queryBuilder->andWhere('a.publishedAt > :after')
214
                ->setParameter('after', $criteria->get('publishedAfter'));
215
            $criteria->remove('publishedAfter');
216
        }
217
218
        if ($criteria->has('query') && strlen($query = trim($criteria->get('query'))) > 0) {
219
            $like = $queryBuilder->expr()->like('a.title', $queryBuilder->expr()->literal('%'.$query.'%'));
220
221
            $queryBuilder->andWhere($like);
222
            $criteria->remove('query');
223
        }
224
225 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...
226
            $articleSourcesQueryBuilder = $this->getEntityManager()
227
                ->createQueryBuilder()
228
                ->select('excluded_article.id')
229
                ->from(ArticleSourceReference::class, 'excluded_asr')
230
                ->join('excluded_asr.article', 'excluded_article')
231
                ->join('excluded_asr.articleSource', 'excluded_articleSource');
232
233
            $orX = $queryBuilder->expr()->orX();
234
            foreach ((array) $criteria->get('exclude_source') as $value) {
235
                $orX->add($articleSourcesQueryBuilder->expr()->eq('excluded_articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
236
            }
237
            $articleSourcesQueryBuilder->andWhere($orX);
238
            $queryBuilder->andWhere($queryBuilder->expr()->notIn('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
239
240
            $criteria->remove('exclude_source');
241
        }
242
243 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...
244
            $articleSourcesQueryBuilder = $this->getEntityManager()
245
                ->createQueryBuilder()
246
                ->select('article.id')
247
                ->from(ArticleSourceReference::class, 'asr')
248
                ->join('asr.article', 'article')
249
                ->join('asr.articleSource', 'articleSource');
250
            $orX = $queryBuilder->expr()->orX();
251
            foreach ((array) $criteria->get('source') as $value) {
252
                $orX->add($articleSourcesQueryBuilder->expr()->eq('articleSource.name', $articleSourcesQueryBuilder->expr()->literal($value)));
253
            }
254
            $articleSourcesQueryBuilder->andWhere($orX);
255
            $queryBuilder->andWhere($queryBuilder->expr()->in('a.id', $articleSourcesQueryBuilder->getQuery()->getDQL()));
256
257
            $criteria->remove('source');
258
        }
259
260 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...
261
            $orX = $queryBuilder->expr()->orX();
262
            foreach ((array) $criteria->get('author') as $value) {
263
                $orX->add($queryBuilder->expr()->eq('au.name', $queryBuilder->expr()->literal($value)));
264
            }
265
266
            $queryBuilder->andWhere($orX);
267
            $criteria->remove('author');
268
        }
269
270 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...
271
            $andX = $queryBuilder->expr()->andX();
272
            foreach ((array) $criteria->get('exclude_author') as $value) {
273
                $andX->add($queryBuilder->expr()->neq('au.name', $queryBuilder->expr()->literal($value)));
274
            }
275
276
            $queryBuilder->andWhere($andX);
277
            $criteria->remove('author');
278
        }
279
    }
280
}
281