Completed
Pull Request — master (#53)
by Benjamin
02:36
created

AdminNode::createQuery()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 44
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 44
rs 6.7272
cc 7
eloc 25
nc 16
nop 1
1
<?php
2
3
namespace Alpixel\Bundle\CMSBundle\Admin;
4
5
use Doctrine\DBAL\Query\QueryBuilder;
6
use Knp\Menu\ItemInterface as MenuItemInterface;
7
use Sonata\AdminBundle\Datagrid\DatagridMapper;
8
use Sonata\AdminBundle\Datagrid\ListMapper;
9
use Sonata\AdminBundle\Route\RouteCollection;
10
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
11
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
12
13
class AdminNode extends BaseAdmin
14
{
15
    protected $baseRouteName = 'alpixel_admin_cms_node';
16
    protected $baseRoutePattern = 'node';
17
    protected $classnameLabel = 'pages';
18
19
    protected $datagridValues = [
20
        '_page' => 1,
21
        '_sort_order' => 'DESC',
22
        '_sort_by' => 'dateUpdated',
23
    ];
24
25
    protected function configureRoutes(RouteCollection $collection)
26
    {
27
        $collection->clearExcept(['list', 'batch', 'delete']);
28
        $collection->add('forwardEdit');
29
    }
30
31
    /**
32
     * @param \Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper
33
     *
34
     * @return void
35
     */
36
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
37
    {
38
        $container = $this->getConfigurationPool()->getContainer();
39
        $entityManager = $container->get('doctrine.orm.default_entity_manager');
40
        $datagridMapper
41
            ->add('locale', 'doctrine_orm_callback', [
42
                'label' => 'Langue',
43
                'callback' => function (ProxyQuery $queryBuilder, $alias, $field, $value) {
44
                    if (!$value['value']) {
45
                        return false;
46
                    }
47
                    $queryBuilder
48
                        ->andWhere($alias . '.locale = :locale')
49
                        ->setParameter('locale', $value['value']);
50
51
                    return true;
52
                },
53
            ],
54
                'choice',
55
                [
56
                    'choices' => $this->getRealLocales(),
57
                ])
58
            ->add('title', null, [
59
                'label' => 'Page',
60
            ])
61
            ->add('published', null, [
62
                'label' => 'Publié',
63
            ])
64
            ->add('node', 'doctrine_orm_callback', [
65
                'label' => 'Type de contenu',
66
                'callback' => function (ProxyQuery $queryBuilder, $alias, $field, $value) use ($entityManager) {
67
                    if (!$value['value']) {
68
                        return false;
69
                    }
70
                    // We can't query the type from the AlpixelCMSBundle:Node repository (InheritanceType) because of that
71
                    // we try to get the repository in AppBundle with the value which is the class name of entity. :pig:
72
                    try {
73
                        $repository = $entityManager->getRepository(sprintf('AppBundle:%s', ucfirst($value['value'])));
74
                    } catch (\Doctrine\Common\Persistence\Mapping\MappingException $e) {
75
                        return false;
76
                    }
77
                    $data = $repository->findAll();
78
                    if (empty($data)) {
79
                        return false;
80
                    }
81
                    $queryBuilder
82
                        ->andWhere($alias . '.id IN (:ids)')
83
                        ->setParameter('ids', $data);
84
85
                    return true;
86
                },
87
            ],
88
                'choice',
89
                [
90
                    'choices' => $this->getCMSEntityTypes(),
91
                ]
92
            );
93
    }
94
95
    /**
96
     * @param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
97
     *
98
     * @return void
99
     */
100
    protected function configureListFields(ListMapper $listMapper)
101
    {
102
        $listMapper
103
            ->add('id')
104
            ->add('locale', null, [
105
                'label' => 'Langue',
106
            ])
107
            ->add('title', null, [
108
                'label' => 'Page',
109
            ])
110
            ->add('type', null, [
111
                'label' => 'Type',
112
                'template' => 'AlpixelCMSBundle:admin:fields/list__field_type.html.twig',
113
            ])
114
            ->add('dateCreated', null, [
115
                'label' => 'Date de création',
116
            ])
117
            ->add('dateUpdated', null, [
118
                'label' => 'Date d\'édition',
119
            ])
120
            ->add('published', null, [
121
                'label' => 'Publié',
122
            ])
123
            ->add('_action', 'actions', [
124
                'actions' => [
125
                    'see' => ['template' => 'AlpixelCMSBundle:admin:fields/list__action_see.html.twig'],
126
                    'edit' => ['template' => 'AlpixelCMSBundle:admin:fields/list__action_edit.html.twig'],
127
                    'delete' => ['template' => 'AlpixelCMSBundle:admin:fields/list__action_delete.html.twig'],
128
                ],
129
            ]);
130
    }
131
132
    public function buildBreadcrumbs($action, MenuItemInterface $menu = null)
133
    {
134
        if (isset($this->breadcrumbs[$action])) {
135
            return $this->breadcrumbs[$action];
136
        }
137
138
        $menu = $this->menuFactory->createItem('root');
139
140
        $menu = $menu->addChild('Dashboard',
141
            ['uri' => $this->routeGenerator->generate('sonata_admin_dashboard')]
142
        );
143
144
        $menu = $menu->addChild('Gestion des pages',
145
            ['uri' => $this->routeGenerator->generate('alpixel_admin_cms_node_list')]
146
        );
147
148
        return $this->breadcrumbs[$action] = $menu;
149
    }
150
151
    public function createQuery($context = 'list')
152
    {
153
        $container = $this->getConfigurationPool()->getContainer();
154
        $entityManager = $container->get('doctrine.orm.entity_manager');
155
156
        $query = parent::createQuery($context);
157
158
        if ($this->isGranted('ROLE_SONATA_ADMIN') === false) {
159
            $contentTypes = $this->getCMSTypes();
160
161
            $viewableCMS = [];
162
            foreach ($contentTypes as $key => $contentType) {
163
                try {
164
                    if (isset($contentType['admin'])) {
165
                        $contentType['admin']->checkAccess("list"); //Throw an exception if doesn' have access
166
                        $viewableCMS[$key] = $contentType;
167
                    }
168
                } catch (AccessDeniedException $e) {
169
170
                }
171
            }
172
173
            $queryBuilder = clone $query;
174
            /** @var QueryBuilder $queryBuilder */
175
176
            $orX = $queryBuilder->expr()->orX();
177
            $orX->add($queryBuilder->expr()->eq('2', '1'));
178
179
            foreach ($viewableCMS as $key => $viewableContent) {
180
                $nodes = $entityManager->getRepository($viewableContent['class'])->findAll();
181
                $nodesId = [];
182
183
                foreach($nodes as $node) {
184
                    $nodesId[] = $node->getId();
185
                }
186
187
                $orX->add($queryBuilder->expr()->in($queryBuilder->getRootAlias() . '.id', $nodesId));
0 ignored issues
show
Bug introduced by
The method getRootAlias() does not seem to exist on object<Doctrine\DBAL\Query\QueryBuilder>.

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...
188
            }
189
            $queryBuilder->andWhere($orX);
190
            return $queryBuilder;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $queryBuilder; (Doctrine\DBAL\Query\QueryBuilder) is incompatible with the return type declared by the interface Sonata\AdminBundle\Admin...nInterface::createQuery of type Sonata\AdminBundle\Datagrid\ProxyQueryInterface.

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...
191
        }
192
193
        return $query;
194
    }
195
196
}
197