PostManager::getPager()   F
last analyzed

Complexity

Conditions 13
Paths 384

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 67
rs 3.5066
c 0
b 0
f 0
cc 13
nc 384
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\NewsBundle\Entity;
15
16
use Doctrine\ORM\Query\Expr\Join;
17
use Sonata\ClassificationBundle\Model\CollectionInterface;
18
use Sonata\DatagridBundle\Pager\Doctrine\Pager;
19
use Sonata\DatagridBundle\ProxyQuery\Doctrine\ProxyQuery;
20
use Sonata\Doctrine\Entity\BaseEntityManager;
21
use Sonata\NewsBundle\Model\BlogInterface;
22
use Sonata\NewsBundle\Model\PostManagerInterface;
23
24
class PostManager extends BaseEntityManager implements PostManagerInterface
25
{
26
    /**
27
     * @param string $permalink
28
     *
29
     * @return PostInterface|null
30
     */
31
    public function findOneByPermalink($permalink, BlogInterface $blog)
32
    {
33
        $query = $this->getRepository()->createQueryBuilder('p');
34
35
        try {
36
            $urlParameters = $blog->getPermalinkGenerator()->getParameters($permalink);
37
        } catch (\InvalidArgumentException $exception) {
38
            return null;
39
        }
40
41
        $parameters = [];
42
43
        if (isset($urlParameters['year'], $urlParameters['month'], $urlParameters['day'])) {
44
            $dateQueryParts = $this->getPublicationDateQueryParts(
45
                sprintf('%d-%d-%d', $urlParameters['year'], $urlParameters['month'], $urlParameters['day']),
46
                'day'
47
            );
48
49
            $parameters = $dateQueryParts['params'];
50
51
            $query->andWhere($dateQueryParts['query']);
52
        }
53
54
        if (isset($urlParameters['slug'])) {
55
            $query->andWhere('p.slug = :slug');
56
            $parameters['slug'] = $urlParameters['slug'];
57
        }
58
59
        if (isset($urlParameters['collection'])) {
60
            $collectionQueryParts = $this->getPublicationCollectionQueryParts($urlParameters['collection']);
61
62
            $parameters = array_merge($parameters, $collectionQueryParts['params']);
63
64
            $query
65
                ->leftJoin('p.collection', 'c')
66
                ->andWhere($collectionQueryParts['query']);
67
        }
68
69
        if (0 === \count($parameters)) {
70
            return null;
71
        }
72
73
        $query->setParameters($parameters);
74
75
        return $query->getQuery()->getOneOrNullResult();
76
    }
77
78
    /**
79
     * Valid criteria are:
80
     *    enabled - boolean
81
     *    date - query
82
     *    tag - string
83
     *    author - 'NULL', 'NOT NULL', id, array of ids
84
     *    collections - CollectionInterface
85
     *    mode - string public|admin.
86
     */
87
    public function getPager(array $criteria, $page, $limit = 10, array $sort = [])
88
    {
89
        if (!isset($criteria['mode'])) {
90
            $criteria['mode'] = 'public';
91
        }
92
93
        $parameters = [];
94
        $query = $this->getRepository()
95
            ->createQueryBuilder('p')
96
            ->select('p, t')
97
            ->orderBy('p.publicationDateStart', 'DESC');
98
99
        if ('admin' === $criteria['mode']) {
100
            $query
101
                ->leftJoin('p.tags', 't')
102
                ->leftJoin('p.author', 'a')
103
            ;
104
        } else {
105
            $query
106
                ->leftJoin('p.tags', 't', Join::WITH, 't.enabled = true')
107
                ->leftJoin('p.author', 'a', Join::WITH, 'a.enabled = true')
108
            ;
109
        }
110
111
        if (!isset($criteria['enabled']) && 'public' === $criteria['mode']) {
112
            $criteria['enabled'] = true;
113
        }
114
        if (isset($criteria['enabled'])) {
115
            $query->andWhere('p.enabled = :enabled');
116
            $parameters['enabled'] = $criteria['enabled'];
117
        }
118
119
        if (isset($criteria['date'], $criteria['date']['query'], $criteria['date']['params'])) {
120
            $query->andWhere($criteria['date']['query']);
121
            $parameters = array_merge($parameters, $criteria['date']['params']);
122
        }
123
124
        if (isset($criteria['tag'])) {
125
            $query
126
                ->leftJoin('p.tags', 't2')
127
                ->andWhere('t2.slug LIKE :tag');
128
            $parameters['tag'] = (string) $criteria['tag'];
129
        }
130
131
        if (isset($criteria['author'])) {
132
            if (!\is_array($criteria['author']) && stristr($criteria['author'], 'NULL')) {
133
                $query->andWhere('p.author IS '.$criteria['author']);
134
            } else {
135
                $query->andWhere(sprintf('p.author IN (%s)', implode(',', (array) $criteria['author'])));
136
            }
137
        }
138
139
        if (isset($criteria['collection']) && $criteria['collection'] instanceof CollectionInterface) {
140
            $query->andWhere('p.collection = :collectionid');
141
            $parameters['collectionid'] = $criteria['collection']->getId();
0 ignored issues
show
Bug introduced by
The method getId() does not seem to exist on object<Sonata\Classifica...el\CollectionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
142
        }
143
144
        $query->setParameters($parameters);
145
146
        $pager = new Pager();
147
        $pager->setMaxPerPage($limit);
148
        $pager->setQuery(new ProxyQuery($query));
149
        $pager->setPage($page);
150
        $pager->init();
151
152
        return $pager;
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function getPublicationDateQueryParts($date, $step, $alias = 'p')
159
    {
160
        return [
161
            'query' => sprintf('%s.publicationDateStart >= :startDate AND %s.publicationDateStart < :endDate', $alias, $alias),
162
            'params' => [
163
                'startDate' => new \DateTime($date),
164
                'endDate' => new \DateTime($date.'+1 '.$step),
165
            ],
166
        ];
167
    }
168
169
    /**
170
     * @param string $collection
171
     *
172
     * @return array
173
     */
174
    protected function getPublicationCollectionQueryParts($collection)
175
    {
176
        $queryParts = ['query' => '', 'params' => []];
177
178
        if (null === $collection) {
179
            $queryParts['query'] = 'p.collection IS NULL';
180
        } else {
181
            $queryParts['query'] = 'c.slug = :collection';
182
            $queryParts['params'] = ['collection' => $collection];
183
        }
184
185
        return $queryParts;
186
    }
187
}
188