Completed
Push — 3.x ( 733455...aa9981 )
by Grégoire
02:00
created

PostManager::getPager()   F

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
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\NewsBundle\Entity;
13
14
use Doctrine\ORM\Query\Expr\Join;
15
use Sonata\ClassificationBundle\Model\CollectionInterface;
16
use Sonata\CoreBundle\Model\BaseEntityManager;
17
use Sonata\DatagridBundle\Pager\Doctrine\Pager;
18
use Sonata\DatagridBundle\ProxyQuery\Doctrine\ProxyQuery;
19
use Sonata\NewsBundle\Model\BlogInterface;
20
use Sonata\NewsBundle\Model\PostInterface;
21
use Sonata\NewsBundle\Model\PostManagerInterface;
22
23
class PostManager extends BaseEntityManager implements PostManagerInterface
24
{
25
    /**
26
     * @param string        $permalink
27
     * @param BlogInterface $blog
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
     * {@inheritdoc}
80
     *
81
     * Valid criteria are:
82
     *    enabled - boolean
83
     *    date - query
84
     *    tag - string
85
     *    author - 'NULL', 'NOT NULL', id, array of ids
86
     *    collections - CollectionInterface
87
     *    mode - string public|admin
88
     */
89
    public function getPager(array $criteria, $page, $limit = 10, array $sort = [])
90
    {
91
        if (!isset($criteria['mode'])) {
92
            $criteria['mode'] = 'public';
93
        }
94
95
        $parameters = [];
96
        $query = $this->getRepository()
97
            ->createQueryBuilder('p')
98
            ->select('p, t')
99
            ->orderBy('p.publicationDateStart', 'DESC');
100
101
        if ('admin' == $criteria['mode']) {
102
            $query
103
                ->leftJoin('p.tags', 't')
104
                ->leftJoin('p.author', 'a')
105
            ;
106
        } else {
107
            $query
108
                ->leftJoin('p.tags', 't', Join::WITH, 't.enabled = true')
109
                ->leftJoin('p.author', 'a', Join::WITH, 'a.enabled = true')
110
            ;
111
        }
112
113
        if (!isset($criteria['enabled']) && 'public' == $criteria['mode']) {
114
            $criteria['enabled'] = true;
115
        }
116
        if (isset($criteria['enabled'])) {
117
            $query->andWhere('p.enabled = :enabled');
118
            $parameters['enabled'] = $criteria['enabled'];
119
        }
120
121
        if (isset($criteria['date'], $criteria['date']['query'], $criteria['date']['params'])) {
122
            $query->andWhere($criteria['date']['query']);
123
            $parameters = array_merge($parameters, $criteria['date']['params']);
124
        }
125
126
        if (isset($criteria['tag'])) {
127
            $query
128
                ->leftJoin('p.tags', 't2')
129
                ->andWhere('t2.slug LIKE :tag');
130
            $parameters['tag'] = (string) $criteria['tag'];
131
        }
132
133
        if (isset($criteria['author'])) {
134
            if (!is_array($criteria['author']) && stristr($criteria['author'], 'NULL')) {
135
                $query->andWhere('p.author IS '.$criteria['author']);
136
            } else {
137
                $query->andWhere(sprintf('p.author IN (%s)', implode((array) $criteria['author'], ',')));
138
            }
139
        }
140
141
        if (isset($criteria['collection']) && $criteria['collection'] instanceof CollectionInterface) {
142
            $query->andWhere('p.collection = :collectionid');
143
            $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...
144
        }
145
146
        $query->setParameters($parameters);
147
148
        $pager = new Pager();
149
        $pager->setMaxPerPage($limit);
150
        $pager->setQuery(new ProxyQuery($query));
151
        $pager->setPage($page);
152
        $pager->init();
153
154
        return $pager;
155
    }
156
157
    /**
158
     * @param string $date  Date in format YYYY-MM-DD
159
     * @param string $step  Interval step: year|month|day
160
     * @param string $alias Table alias for the publicationDateStart column
161
     *
162
     * @return array
163
     */
164
    public function getPublicationDateQueryParts($date, $step, $alias = 'p')
165
    {
166
        return [
167
            'query' => sprintf('%s.publicationDateStart >= :startDate AND %s.publicationDateStart < :endDate', $alias, $alias),
168
            'params' => [
169
                'startDate' => new \DateTime($date),
170
                'endDate' => new \DateTime($date.'+1 '.$step),
171
            ],
172
        ];
173
    }
174
175
    /**
176
     * @param string $collection
177
     *
178
     * @return array
179
     */
180
    protected function getPublicationCollectionQueryParts($collection)
181
    {
182
        $queryParts = ['query' => '', 'params' => []];
183
184
        if (null === $collection) {
185
            $queryParts['query'] = 'p.collection IS NULL';
186
        } else {
187
            $queryParts['query'] = 'c.slug = :collection';
188
            $queryParts['params'] = ['collection' => $collection];
189
        }
190
191
        return $queryParts;
192
    }
193
}
194