Completed
Push — master ( c3ce72...f2565d )
by Paweł
20s
created

ArticleRepository::findAllArticles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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