Completed
Push — master ( 619948...d55d2c )
by
unknown
02:29
created

PostManager::getPublicationCollectionQueryParts()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
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\Document;
13
14
use Sonata\CoreBundle\Model\BaseDocumentManager;
15
use Sonata\DoctrineMongoDBAdminBundle\Datagrid\Pager;
16
use Sonata\DoctrineMongoDBAdminBundle\Datagrid\ProxyQuery;
17
use Sonata\NewsBundle\Model\BlogInterface;
18
use Sonata\NewsBundle\Model\PostManagerInterface;
19
20
class PostManager extends BaseDocumentManager implements PostManagerInterface
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public function findOneByPermalink($permalink, BlogInterface $blog)
26
    {
27
        $query = $this->getRepository()->createQueryBuilder('p');
28
29
        $urlParameters = $blog->getPermalinkGenerator()->getParameters($permalink);
30
31
        $parameters = array();
32
33
        if (isset($urlParameters['year'], $urlParameters['month'], $urlParameters['day'])) {
34
            $dateQueryParts = $this->getPublicationDateQueryParts(
35
                sprintf('%d-%d-%d', $urlParameters['year'], $urlParameters['month'], $urlParameters['day']),
36
                'day'
37
            );
38
39
            $parameters = $dateQueryParts['params'];
40
41
            $query->andWhere($dateQueryParts['query']);
42
        }
43
44
        if (isset($urlParameters['slug'])) {
45
            $query->andWhere('p.slug = :slug');
46
            $parameters['slug'] = $urlParameters['slug'];
47
        }
48
49
        if (isset($urlParameters['collection'])) {
50
            $collectionQueryParts = $this->getPublicationCollectionQueryParts($urlParameters['collection']);
51
52
            $parameters = array_merge($parameters, $collectionQueryParts['params']);
53
54
            $query
55
                ->leftJoin('p.collection', 'c')
56
                ->andWhere($collectionQueryParts['query']);
57
        }
58
59
        if (count($parameters) == 0) {
60
            return;
61
        }
62
63
        $query->setParameters($parameters);
64
65
        return $query->getQuery()->getSingleResult();
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     *
71
     * Valid criteria are:
72
     *    enabled - boolean
73
     *    date - query
74
     *    tag - string
75
     *    author - 'NULL', 'NOT NULL', id, array of ids
76
     *    collections - CollectionInterface
77
     *    mode - string public|admin
78
     */
79
    public function getPager(array $criteria, $page, $limit = 10, array $sort = array())
80
    {
81
        if (!isset($criteria['mode'])) {
82
            $criteria['mode'] = 'public';
83
        }
84
85
        $parameters = array();
86
        $query = $this->getRepository()
87
            ->createQueryBuilder('p')
88
            ->select('p, t')
89
            ->leftJoin('p.tags', 't')
90
            ->orderBy('p.publicationDateStart', 'DESC');
91
92
        if (!isset($criteria['enabled']) && $criteria['mode'] == 'public') {
93
            $criteria['enabled'] = true;
94
        }
95
        if (isset($criteria['enabled'])) {
96
            $query->andWhere('p.enabled = :enabled');
97
            $parameters['enabled'] = $criteria['enabled'];
98
        }
99
100
        if (isset($criteria['date'], $criteria['date']['query'], $criteria['date']['params'])) {
101
            $query->andWhere($criteria['date']['query']);
102
            $parameters = array_merge($parameters, $criteria['date']['params']);
103
        }
104
105
        if (isset($criteria['tag'])) {
106
            $query->andWhere('t.slug LIKE :tag');
107
            $parameters['tag'] = (string) $criteria['tag'];
108
        }
109
110
        if (isset($criteria['author'])) {
111
            if (!is_array($criteria['author']) && stristr($criteria['author'], 'NULL')) {
112
                $query->andWhere('p.author IS '.$criteria['author']);
113
            } else {
114
                $query->andWhere(sprintf('p.author IN (%s)', implode((array) $criteria['author'], ',')));
115
            }
116
        }
117
118
        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...
119
            $query->andWhere('p.collection = :collectionid');
120
            $parameters['collectionid'] = $criteria['collection']->getId();
121
        }
122
123
        $query->setParameters($parameters);
124
125
        $pager = new Pager();
126
        $pager->setMaxPerPage($limit);
127
        $pager->setQuery(new ProxyQuery($query));
128
        $pager->setPage($page);
129
        $pager->init();
130
131
        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\CoreBundle\Model\...agerInterface::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...
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function getPublicationDateQueryParts($date, $step, $alias = 'p')
138
    {
139
        return array(
140
            'query' => sprintf('%s.publicationDateStart >= :startDate AND %s.publicationDateStart < :endDate', $alias, $alias),
141
            'params' => array(
142
                'startDate' => new \DateTime($date),
143
                'endDate' => new \DateTime($date.'+1 '.$step),
144
            ),
145
        );
146
    }
147
148
    /**
149
     * @param string $collection
150
     *
151
     * @return array
152
     */
153
    final protected function getPublicationCollectionQueryParts($collection)
154
    {
155
        $queryParts = array('query' => '', 'params' => array());
156
157
        if (null === $collection) {
158
            $queryParts['query'] = 'p.collection IS NULL';
159
        } else {
160
            $queryParts['query'] = 'c.slug = :collection';
161
            $queryParts['params'] = array('collection' => $collection);
162
        }
163
164
        return $queryParts;
165
    }
166
}
167