Completed
Pull Request — master (#299)
by Christian
03:01
created

PostManager::findOneBySlug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 4
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
     * {@inheritdoc}
25
     */
26
    public function findOneByPermalink($permalink, BlogInterface $blog)
27
    {
28
        $query = $this->getRepository()->createQueryBuilder('p');
29
30
        $urlParameters = $blog->getPermalinkGenerator()->getParameters($permalink);
31
32
        $parameters = array();
33
34
        if (isset($urlParameters['year'], $urlParameters['month'], $urlParameters['day'])) {
35
            $dateQueryParts = $this->getPublicationDateQueryParts(
36
                sprintf('%d-%d-%d', $urlParameters['year'], $urlParameters['month'], $urlParameters['day']),
37
                'day'
38
            );
39
40
            $parameters = $dateQueryParts['params'];
41
42
            $query->andWhere($dateQueryParts['query']);
43
        }
44
45
        if (isset($urlParameters['slug'])) {
46
            $query->andWhere('p.slug = :slug');
47
            $parameters['slug'] = $urlParameters['slug'];
48
        }
49
50
        if (isset($urlParameters['collection'])) {
51
            $collectionQueryParts = $this->getPublicationCollectionQueryParts($urlParameters['collection']);
52
53
            $parameters = array_merge($parameters, $collectionQueryParts['params']);
54
55
            $query
56
                ->leftJoin('p.collection', 'c')
57
                ->andWhere($collectionQueryParts['query']);
58
        }
59
60
        if (count($parameters) == 0) {
61
            return;
62
        }
63
64
        $query->setParameters($parameters);
65
66
        return $query->getQuery()->getSingleResult();
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getPager(array $criteria, $page, $limit = 10, array $sort = array())
73
    {
74
        $parameters = array();
75
        $query = $this->getRepository()
76
            ->createQueryBuilder('p')
77
            ->select('p, t')
78
            ->leftJoin('p.tags', 't')
79
            ->orderby('p.publicationDateStart', 'DESC');
80
81
        // enabled
82
        $criteria['enabled'] = isset($criteria['enabled']) ? $criteria['enabled'] : true;
83
        $query->andWhere('p.enabled = :enabled');
84
        $parameters['enabled'] = $criteria['enabled'];
85
86
        if (isset($criteria['date'])) {
87
            $query->andWhere($criteria['date']['query']);
88
            $parameters = array_merge($parameters, $criteria['date']['params']);
89
        }
90
91
        if (isset($criteria['tag'])) {
92
            $query->andWhere('t.slug LIKE :tag and t.enabled = :tag_enabled');
93
            $parameters['tag'] = $criteria['tag'];
94
            $parameters['tag_enabled'] = true;
95
        }
96
97
        $query->setParameters($parameters);
98
99
        $pager = new Pager();
100
        $pager->setQuery(new ProxyQuery($query));
101
        $pager->setPage($page);
102
        $pager->init();
103
104
        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...
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110
    public function getPublicationDateQueryParts($date, $step, $alias = 'p')
111
    {
112
        return array(
113
            'query' => sprintf('%s.publicationDateStart >= :startDate AND %s.publicationDateStart < :endDate', $alias, $alias),
114
            'params' => array(
115
                'startDate' => new \DateTime($date),
116
                'endDate' => new \DateTime($date.'+1 '.$step),
117
            ),
118
        );
119
    }
120
121
    /**
122
     * @param string $collection
123
     *
124
     * @return array
125
     */
126
    final protected function getPublicationCollectionQueryParts($collection)
127
    {
128
        $queryParts = array('query' => '', 'params' => array());
129
130
        if (null === $collection) {
131
            $queryParts['query'] = 'p.collection IS NULL';
132
        } else {
133
            $queryParts['query'] = 'c.slug = :collection';
134
            $queryParts['params'] = array('collection' => $collection);
135
        }
136
137
        return $queryParts;
138
    }
139
}
140