Completed
Push — 3.x ( 614672...d7881f )
by Sullivan
03:43 queued 30s
created

PostManager::findOneByPermalink()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 42
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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