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

PostManager::findOneByPermalink()   C

Complexity

Conditions 9
Paths 84

Size

Total Lines 50
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 50
rs 6
cc 9
eloc 27
nc 84
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\PostManagerInterface;
19
20
class PostManager extends BaseDocumentManager implements PostManagerInterface
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public function findOneByPermalink($permalink, BlogInterface $blog)
26
    {
27
        $repository = $this->getRepository();
28
29
        $query = $repository->createQueryBuilder('p');
30
31
        try {
32
            $urlParameters = $blog->getPermalinkGenerator()->getParameters($permalink);
33
34
            $parameters = array();
35
36
            if (isset($urlParameters['year']) && isset($urlParameters['month']) && isset($urlParameters['day'])) {
37
                $pdqp = $this->getPublicationDateQueryParts(sprintf('%d-%d-%d', $urlParameters['year'], $urlParameters['month'], $urlParameters['day']), 'day');
38
39
                $parameters = array_merge($parameters, $pdqp['params']);
40
41
                $query->andWhere($pdqp['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
                $pcqp = $this->getPublicationCollectionQueryParts($urlParameters['collection']);
0 ignored issues
show
Bug introduced by
The method getPublicationCollectionQueryParts() does not seem to exist on object<Sonata\NewsBundle\Document\PostManager>.

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...
51
52
                $parameters = array_merge($parameters, $pcqp['params']);
53
54
                $query
55
                    ->leftJoin('p.collection', 'c')
56
                    ->andWhere($pcqp['query']);
57
            }
58
59
            if (count($parameters) == 0) {
60
                return;
61
            }
62
63
            $query->setParameters($parameters);
64
65
            $results = $query->getQuery()->getResult();
66
67
            if (count($results) > 0) {
68
                return $results[0];
69
            }
70
        } catch (\InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
71
        }
72
73
        return;
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function getPager(array $criteria, $page, $limit = 10, array $sort = array())
80
    {
81
        $parameters = array();
82
        $query = $this->getRepository()
83
            ->createQueryBuilder('p')
84
            ->select('p, t')
85
            ->leftJoin('p.tags', 't')
86
            ->orderby('p.publicationDateStart', 'DESC');
87
88
        // enabled
89
        $criteria['enabled'] = isset($criteria['enabled']) ? $criteria['enabled'] : true;
90
        $query->andWhere('p.enabled = :enabled');
91
        $parameters['enabled'] = $criteria['enabled'];
92
93
        if (isset($criteria['date'])) {
94
            $query->andWhere($criteria['date']['query']);
95
            $parameters = array_merge($parameters, $criteria['date']['params']);
96
        }
97
98
        if (isset($criteria['tag'])) {
99
            $query->andWhere('t.slug LIKE :tag and t.enabled = :tag_enabled');
100
            $parameters['tag'] = $criteria['tag'];
101
            $parameters['tag_enabled'] = true;
102
        }
103
104
        $query->setParameters($parameters);
105
106
        $pager = new Pager();
107
        $pager->setQuery(new ProxyQuery($query));
108
        $pager->setPage($page);
109
        $pager->init();
110
111
        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...
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function getPublicationDateQueryParts($date, $step, $alias = 'p')
118
    {
119
        return array(
120
            'query' => sprintf('%s.publicationDateStart >= :startDate AND %s.publicationDateStart < :endDate', $alias, $alias),
121
            'params' => array(
122
                'startDate' => new \DateTime($date),
123
                'endDate' => new \DateTime($date.'+1 '.$step),
124
            ),
125
        );
126
    }
127
}
128