PostManager::getPager()   C
last analyzed

Complexity

Conditions 12
Paths 192

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 6.2
c 0
b 0
f 0
cc 12
nc 192
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\Document;
15
16
use Sonata\Doctrine\Document\BaseDocumentManager;
17
use Sonata\DoctrineMongoDBAdminBundle\Datagrid\Pager;
18
use Sonata\DoctrineMongoDBAdminBundle\Datagrid\ProxyQuery;
19
use Sonata\NewsBundle\Model\BlogInterface;
20
use Sonata\NewsBundle\Model\PostManagerInterface;
21
22
class PostManager extends BaseDocumentManager implements PostManagerInterface
23
{
24
    /**
25
     * @param string $permalink
26
     *
27
     * @return PostInterface|null
28
     */
29
    public function findOneByPermalink($permalink, BlogInterface $blog)
30
    {
31
        $query = $this->getRepository()->createQueryBuilder('p');
32
33
        try {
34
            $urlParameters = $blog->getPermalinkGenerator()->getParameters($permalink);
35
        } catch (\InvalidArgumentException $exception) {
36
            return null;
37
        }
38
39
        $parameters = [];
40
41
        if (isset($urlParameters['year'], $urlParameters['month'], $urlParameters['day'])) {
42
            $dateQueryParts = $this->getPublicationDateQueryParts(
43
                sprintf('%d-%d-%d', $urlParameters['year'], $urlParameters['month'], $urlParameters['day']),
44
                'day'
45
            );
46
47
            $parameters = $dateQueryParts['params'];
48
49
            $query->andWhere($dateQueryParts['query']);
50
        }
51
52
        if (isset($urlParameters['slug'])) {
53
            $query->andWhere('p.slug = :slug');
54
            $parameters['slug'] = $urlParameters['slug'];
55
        }
56
57
        if (isset($urlParameters['collection'])) {
58
            $collectionQueryParts = $this->getPublicationCollectionQueryParts($urlParameters['collection']);
59
60
            $parameters = array_merge($parameters, $collectionQueryParts['params']);
61
62
            $query
63
                ->leftJoin('p.collection', 'c')
64
                ->andWhere($collectionQueryParts['query']);
65
        }
66
67
        if (0 === \count($parameters)) {
68
            return null;
69
        }
70
71
        $query->setParameters($parameters);
72
73
        return $query->getQuery()->getOneOrNullResult();
74
    }
75
76
    /**
77
     * Valid criteria are:
78
     *    enabled - boolean
79
     *    date - query
80
     *    tag - string
81
     *    author - 'NULL', 'NOT NULL', id, array of ids
82
     *    collections - CollectionInterface
83
     *    mode - string public|admin.
84
     */
85
    public function getPager(array $criteria, $page, $limit = 10, array $sort = [])
86
    {
87
        if (!isset($criteria['mode'])) {
88
            $criteria['mode'] = 'public';
89
        }
90
91
        $parameters = [];
92
        $query = $this->getRepository()
93
            ->createQueryBuilder('p')
94
            ->select('p, t')
95
            ->leftJoin('p.tags', 't')
96
            ->orderBy('p.publicationDateStart', 'DESC');
97
98
        if (!isset($criteria['enabled']) && 'public' === $criteria['mode']) {
99
            $criteria['enabled'] = true;
100
        }
101
        if (isset($criteria['enabled'])) {
102
            $query->andWhere('p.enabled = :enabled');
103
            $parameters['enabled'] = $criteria['enabled'];
104
        }
105
106
        if (isset($criteria['date'], $criteria['date']['query'], $criteria['date']['params'])) {
107
            $query->andWhere($criteria['date']['query']);
108
            $parameters = array_merge($parameters, $criteria['date']['params']);
109
        }
110
111
        if (isset($criteria['tag'])) {
112
            $query->andWhere('t.slug LIKE :tag');
113
            $parameters['tag'] = (string) $criteria['tag'];
114
        }
115
116
        if (isset($criteria['author'])) {
117
            if (!\is_array($criteria['author']) && stristr($criteria['author'], 'NULL')) {
118
                $query->andWhere('p.author IS '.$criteria['author']);
119
            } else {
120
                $query->andWhere(sprintf('p.author IN (%s)', implode(',', (array) $criteria['author'])));
121
            }
122
        }
123
124
        if (isset($criteria['collection']) && $criteria['collection'] instanceof CollectionInterface) {
0 ignored issues
show
Bug introduced by
The class Sonata\NewsBundle\Document\CollectionInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
125
            $query->andWhere('p.collection = :collectionid');
126
            $parameters['collectionid'] = $criteria['collection']->getId();
127
        }
128
129
        $query->setParameters($parameters);
130
131
        $pager = new Pager();
132
        $pager->setMaxPerPage($limit);
133
        $pager->setQuery(new ProxyQuery($query));
134
        $pager->setPage($page);
135
        $pager->init();
136
137
        return $pager;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $pager; (Sonata\DoctrineMongoDBAdminBundle\Datagrid\Pager) is incompatible with the return type declared by the interface Sonata\DatagridBundle\Pa...ableInterface::getPager of type Sonata\DatagridBundle\Pager\PagerInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
138
    }
139
140
    public function getPublicationDateQueryParts($date, $step, $alias = 'p')
141
    {
142
        return [
143
            'query' => sprintf('%s.publicationDateStart >= :startDate AND %s.publicationDateStart < :endDate', $alias, $alias),
144
            'params' => [
145
                'startDate' => new \DateTime($date),
146
                'endDate' => new \DateTime($date.'+1 '.$step),
147
            ],
148
        ];
149
    }
150
151
    /**
152
     * @param string $collection
153
     *
154
     * @return array
155
     */
156
    final protected function getPublicationCollectionQueryParts($collection)
157
    {
158
        $queryParts = ['query' => '', 'params' => []];
159
160
        if (null === $collection) {
161
            $queryParts['query'] = 'p.collection IS NULL';
162
        } else {
163
            $queryParts['query'] = 'c.slug = :collection';
164
            $queryParts['params'] = ['collection' => $collection];
165
        }
166
167
        return $queryParts;
168
    }
169
}
170