Completed
Push — 3.x-dev-kit ( 21be5a )
by
unknown
03:10
created

PostManager::getPager()   D

Complexity

Conditions 15
Paths 384

Size

Total Lines 67
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 67
rs 4.3207
cc 15
eloc 44
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
30
     */
31
    public function findOneByPermalink($permalink, BlogInterface $blog)
32
    {
33
        $repository = $this->getRepository();
34
35
        $query = $repository->createQueryBuilder('p');
36
37
        try {
38
            $urlParameters = $blog->getPermalinkGenerator()->getParameters($permalink);
39
40
            $parameters = array();
41
42
            if (isset($urlParameters['year']) && isset($urlParameters['month']) && isset($urlParameters['day'])) {
43
                $pdqp = $this->getPublicationDateQueryParts(sprintf('%d-%d-%d', $urlParameters['year'], $urlParameters['month'], $urlParameters['day']), 'day');
44
45
                $parameters = array_merge($parameters, $pdqp['params']);
46
47
                $query->andWhere($pdqp['query']);
48
            }
49
50
            if (isset($urlParameters['slug'])) {
51
                $query->andWhere('p.slug = :slug');
52
                $parameters['slug'] = $urlParameters['slug'];
53
            }
54
55
            if (isset($urlParameters['collection'])) {
56
                $pcqp = $this->getPublicationCollectionQueryParts($urlParameters['collection']);
57
58
                $parameters = array_merge($parameters, $pcqp['params']);
59
60
                $query
61
                    ->leftJoin('p.collection', 'c')
62
                    ->andWhere($pcqp['query']);
63
            }
64
65
            if (count($parameters) == 0) {
66
                return;
67
            }
68
69
            $query->setParameters($parameters);
70
71
            $results = $query->getQuery()->getResult();
72
73
            if (count($results) > 0) {
74
                return $results[0];
75
            }
76
        } catch (\InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
77
        }
78
79
        return;
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     *
85
     * Valid criteria are:
86
     *    enabled - boolean
87
     *    date - query
88
     *    tag - string
89
     *    author - 'NULL', 'NOT NULL', id, array of ids
90
     *    collections - CollectionInterface
91
     *    mode - string public|admin
92
     */
93
    public function getPager(array $criteria, $page, $limit = 10, array $sort = array())
94
    {
95
        if (!isset($criteria['mode'])) {
96
            $criteria['mode'] = 'public';
97
        }
98
99
        $parameters = array();
100
        $query = $this->getRepository()
101
            ->createQueryBuilder('p')
102
            ->select('p, t')
103
            ->orderBy('p.publicationDateStart', 'DESC');
104
105
        if ($criteria['mode'] == 'admin') {
106
            $query
107
                ->leftJoin('p.tags', 't')
108
                ->leftJoin('p.author', 'a')
109
            ;
110
        } else {
111
            $query
112
                ->leftJoin('p.tags', 't', Join::WITH, 't.enabled = true')
113
                ->leftJoin('p.author', 'a', Join::WITH, 'a.enabled = true')
114
            ;
115
        }
116
117
        if (!isset($criteria['enabled']) && $criteria['mode'] == 'public') {
118
            $criteria['enabled'] = true;
119
        }
120
        if (isset($criteria['enabled'])) {
121
            $query->andWhere('p.enabled = :enabled');
122
            $parameters['enabled'] = $criteria['enabled'];
123
        }
124
125
        if (isset($criteria['date']) && isset($criteria['date']['query']) && isset($criteria['date']['params'])) {
126
            $query->andWhere($criteria['date']['query']);
127
            $parameters = array_merge($parameters, $criteria['date']['params']);
128
        }
129
130
        if (isset($criteria['tag'])) {
131
            $query
132
                ->leftJoin('p.tags', 't2')
133
                ->andWhere('t2.slug LIKE :tag');
134
            $parameters['tag'] = (string) $criteria['tag'];
135
        }
136
137
        if (isset($criteria['author'])) {
138
            if (!is_array($criteria['author']) && stristr($criteria['author'], 'NULL')) {
139
                $query->andWhere('p.author IS '.$criteria['author']);
140
            } else {
141
                $query->andWhere(sprintf('p.author IN (%s)', implode((array) $criteria['author'], ',')));
142
            }
143
        }
144
145
        if (isset($criteria['collection']) && $criteria['collection'] instanceof CollectionInterface) {
146
            $query->andWhere('p.collection = :collectionid');
147
            $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...
148
        }
149
150
        $query->setParameters($parameters);
151
152
        $pager = new Pager();
153
        $pager->setMaxPerPage($limit);
154
        $pager->setQuery(new ProxyQuery($query));
155
        $pager->setPage($page);
156
        $pager->init();
157
158
        return $pager;
159
    }
160
161
    /**
162
     * @param string $date  Date in format YYYY-MM-DD
163
     * @param string $step  Interval step: year|month|day
164
     * @param string $alias Table alias for the publicationDateStart column
165
     *
166
     * @return array
167
     */
168
    public function getPublicationDateQueryParts($date, $step, $alias = 'p')
169
    {
170
        return array(
171
            'query' => sprintf('%s.publicationDateStart >= :startDate AND %s.publicationDateStart < :endDate', $alias, $alias),
172
            'params' => array(
173
                'startDate' => new \DateTime($date),
174
                'endDate' => new \DateTime($date.'+1 '.$step),
175
            ),
176
        );
177
    }
178
179
    /**
180
     * @param string $collection
181
     *
182
     * @return array
183
     */
184
    protected function getPublicationCollectionQueryParts($collection)
185
    {
186
        $pcqp = array('query' => '', 'params' => array());
187
188
        if (null === $collection) {
189
            $pcqp['query'] = 'p.collection IS NULL';
190
        } else {
191
            $pcqp['query'] = 'c.slug = :collection';
192
            $pcqp['params'] = array('collection' => $collection);
193
        }
194
195
        return $pcqp;
196
    }
197
}
198