AdminNode::createQuery()   B
last analyzed

Complexity

Conditions 8
Paths 26

Size

Total Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 7.9337
c 0
b 0
f 0
cc 8
nc 26
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(
42
                'locale',
43
                'doctrine_orm_callback',
44
                [
45
                    'label'    => 'Langue',
46
                    'callback' => function (ProxyQuery $queryBuilder, $alias, $field, $value) {
47
                        if (!$value['value']) {
48
                            return false;
49
                        }
50
                        $queryBuilder
51
                            ->andWhere($alias.'.locale = :locale')
52
                            ->setParameter('locale', $value['value']);
53
54
                        return true;
55
                    },
56
                ],
57
                'choice',
58
                [
59
                    'choices' => $this->getRealLocales(),
60
                ]
61
            )
62
            ->add(
63
                'title',
64
                null,
65
                [
66
                    'label' => 'Page',
67
                ]
68
            )
69
            ->add(
70
                'published',
71
                null,
72
                [
73
                    'label' => 'Publié',
74
                ]
75
            )
76
            ->add(
77
                'node',
78
                'doctrine_orm_callback',
79
                [
80
                    'label'    => 'Type de contenu',
81
                    'callback' => function (ProxyQuery $queryBuilder, $alias, $field, $value) use ($entityManager) {
82
                        if (!$value['value']) {
83
                            return false;
84
                        }
85
86
                        try {
87
                            $types = $this->getCMSTypes();
88
                            if (array_key_exists($value['value'], $types)) {
89
                                $className = $types[$value['value']]['class'];
90
                                $repository = $entityManager->getRepository($className);
91
                            }
92
                        } catch (\Doctrine\Common\Persistence\Mapping\MappingException $e) {
93
                            return false;
94
                        }
95
                        $data = $repository->findAll();
0 ignored issues
show
Bug introduced by
The variable $repository does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
96
                        if (empty($data)) {
97
                            return false;
98
                        }
99
                        $queryBuilder
100
                            ->andWhere($alias.'.id IN (:ids)')
101
                            ->setParameter('ids', $data);
102
103
                        return true;
104
                    },
105
                ],
106
                'choice',
107
                [
108
                    'choices' => $this->getCMSEntityTypes(),
109
                ]
110
            );
111
    }
112
113
    /**
114
     * @param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
115
     *
116
     * @return void
117
     */
118
    protected function configureListFields(ListMapper $listMapper)
119
    {
120
        $listMapper
121
            ->add('id')
122
            ->add(
123
                'locale',
124
                null,
125
                [
126
                    'label' => 'Langue',
127
                ]
128
            )
129
            ->add(
130
                'title',
131
                null,
132
                [
133
                    'label' => 'Page',
134
                ]
135
            )
136
            ->add(
137
                'type',
138
                null,
139
                [
140
                    'label'    => 'Type',
141
                    'template' => 'AlpixelCMSBundle:admin:fields/list__field_type.html.twig',
142
                ]
143
            )
144
            ->add(
145
                'dateCreated',
146
                null,
147
                [
148
                    'label' => 'Date de création',
149
                ]
150
            )
151
            ->add(
152
                'dateUpdated',
153
                null,
154
                [
155
                    'label' => 'Date d\'édition',
156
                ]
157
            )
158
            ->add(
159
                'published',
160
                null,
161
                [
162
                    'label' => 'Publié',
163
                ]
164
            )
165
            ->add(
166
                '_action',
167
                'actions',
168
                [
169
                    'actions' => [
170
                        'see'    => ['template' => 'AlpixelCMSBundle:admin:fields/list__action_see.html.twig'],
171
                        'edit'   => ['template' => 'AlpixelCMSBundle:admin:fields/list__action_edit.html.twig'],
172
                        'delete' => ['template' => 'AlpixelCMSBundle:admin:fields/list__action_delete.html.twig'],
173
                    ],
174
                ]
175
            );
176
    }
177
178
    public function buildBreadcrumbs($action, MenuItemInterface $menu = null)
179
    {
180
        if (isset($this->breadcrumbs[$action])) {
181
            return $this->breadcrumbs[$action];
182
        }
183
184
        $menu = $this->menuFactory->createItem('root');
185
186
        $menu = $menu->addChild(
187
            'Dashboard',
188
            ['uri' => $this->routeGenerator->generate('sonata_admin_dashboard')]
189
        );
190
191
        $menu = $menu->addChild(
192
            'Gestion des pages',
193
            ['uri' => $this->routeGenerator->generate('alpixel_admin_cms_node_list')]
194
        );
195
196
        return $this->breadcrumbs[$action] = $menu;
197
    }
198
199
    public function createQuery($context = 'list')
200
    {
201
        $container = $this->getConfigurationPool()->getContainer();
202
        $entityManager = $container->get('doctrine.orm.entity_manager');
203
204
        $query = parent::createQuery($context);
205
206
        if ($this->isGranted('ROLE_SONATA_ADMIN') === false) {
207
            $contentTypes = $this->getCMSTypes();
208
209
            $viewableCMS = [];
210
            foreach ($contentTypes as $key => $contentType) {
211
                try {
212
                    if (isset($contentType['admin'])) {
213
                        $contentType['admin']->checkAccess('list'); //Throw an exception if doesn' have access
214
                        $viewableCMS[$key] = $contentType;
215
                    }
216
                } catch (AccessDeniedException $e) {
217
                }
218
            }
219
220
            $queryBuilder = clone $query;
221
            /* @var QueryBuilder $queryBuilder */
222
223
            $orX = $queryBuilder->expr()->orX();
224
            $orX->add($queryBuilder->expr()->eq('2', '1'));
225
226
            foreach ($viewableCMS as $key => $viewableContent) {
227
                $nodes = $entityManager->getRepository($viewableContent['class'])->findAll();
228
                $nodesId = [];
229
230
                foreach ($nodes as $node) {
231
                    $nodesId[] = $node->getId();
232
                }
233
234
                if (count($nodesId) > 0) {
235
                    $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...
236
                }
237
            }
238
            $queryBuilder->andWhere($orX);
239
240
            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...
241
        }
242
243
        return $query;
244
    }
245
}
246