AdminBlockController::redirectTo()   C
last analyzed

Complexity

Conditions 12
Paths 96

Size

Total Lines 38

Duplication

Lines 18
Ratio 47.37 %

Importance

Changes 0
Metric Value
dl 18
loc 38
rs 6.9666
c 0
b 0
f 0
cc 12
nc 96
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Alpixel\Bundle\CMSBundle\Controller;
4
5
use Sonata\AdminBundle\Controller\CRUDController as Controller;
6
use Symfony\Component\HttpFoundation\RedirectResponse;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
9
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
10
11
class AdminBlockController extends Controller
12
{
13
    private $_cmsParameter = 'alpixel_cms.blocks';
14
    private $_cmsContentParameter = null;
15
    private $_blockDefaultClass = 'Alpixel\Bundle\CMSBundle\Entity\Block';
0 ignored issues
show
Unused Code introduced by
The property $_blockDefaultClass is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
16
17
    public function editContentAction()
18
    {
19
        $object = $this->admin->getSubject();
20
        if (!$object) {
21
            throw new NotFoundHttpException(sprintf('unable to find the object'));
22
        }
23
24
        $instanceAdmin = $this->admin->getConfigurationPool()->getAdminByClass(get_class($object));
25
        if ($instanceAdmin !== null) {
26
            return $this->redirect($instanceAdmin->generateUrl('edit', ['id' => $object->getId()]));
27
        }
28
29
        throw new NotFoundHttpException(sprintf('unable to find a class admin for the %s class', get_class($content)));
30
    }
31
32
    public function listAction(Request $request = null)
33
    {
34
        if (false === $this->admin->isGranted('LIST')) {
35
            throw new AccessDeniedException();
36
        }
37
38
        $this->getInstancesAdmin();
39
        // set the theme for the current Admin Form
40
        $datagrid = $this->admin->getDatagrid();
41
        $formView = $datagrid->getForm()->createView();
42
        $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
43
44
        return $this->render($this->admin->getTemplate('list'), [
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...nterface::getTemplate() has been deprecated with message: since 3.35. To be removed in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
Deprecated Code introduced by
The method Sonata\AdminBundle\Contr...RUDController::render() has been deprecated with message: since version 3.27, to be removed in 4.0. Use Sonata\AdminBundle\Controller\CRUDController::renderWithExtraParams() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
45
            'action'         => 'list',
46
            'cmsContentType' => $this->getCMSParameter(),
47
            'form'           => $formView,
48
            'datagrid'       => $datagrid,
49
            'csrf_token'     => $this->getCsrfToken('sonata.batch'),
50
        ], null, $request);
0 ignored issues
show
Unused Code introduced by
The call to AdminBlockController::render() has too many arguments starting with $request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
51
    }
52
53
    /**
54
     *  Set instances of admin in $_cmsContentParameter.
55
     */
56
    protected function getInstancesAdmin()
57
    {
58
        foreach ($this->getCMSParameter() as $key => $value) {
59
            if ($this->checkRolesCMS($value)) {
60
                $instanceAdmin = $this->admin->getConfigurationPool()->getAdminByClass($value['class']);
61
                if ($instanceAdmin !== null) {
62
                    $this->_cmsContentParameter[$key]['admin'] = $instanceAdmin;
63
                }
64
            }
65
        }
66
    }
67
68
    /**
69
     * @param $role array Role in cms.yml
70
     *
71
     * Check role define in different parameter of block or content_types cms.yml
72
     */
73
    protected function checkRolesCMS(array $role)
74
    {
75
        $user = $this->getUser();
76
77
        if (!$user) {
78
            throw new NotFoundHttpException(sprintf('unable to find user'));
79
        }
80
81
        if (!array_key_exists('role', $role) || in_array($user->getRoles()[0], $role['role'])) {
82
            return true;
83
        }
84
85
        return false;
86
    }
87
88
    /**
89
     * Get content in cms.yml and set in $_cmsParameter.
90
     *
91
     * @return content of cms.yml
92
     */
93
    protected function getCMSParameter()
94
    {
95
        if ($this->_cmsContentParameter !== null) {
96
            return $this->_cmsContentParameter;
97
        }
98
99
        $this->_cmsContentParameter = $this->container->getParameter($this->_cmsParameter);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method getParameter() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, ProjectServiceContainer, Symfony\Component\Depend...urationContainerBuilder, Symfony\Component\DependencyInjection\Container, Symfony\Component\Depend...ection\ContainerBuilder, Symfony\Component\Depend...\NoConstructorContainer, Symfony\Component\Depend...tainers\CustomContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony_DI_PhpDumper_Test_Almost_Circular_Private, Symfony_DI_PhpDumper_Test_Almost_Circular_Public, Symfony_DI_PhpDumper_Test_Base64Parameters, Symfony_DI_PhpDumper_Test_EnvParameters, Symfony_DI_PhpDumper_Test_Legacy_Privates, Symfony_DI_PhpDumper_Test_Rot13Parameters, Symfony_DI_PhpDumper_Test_Uninitialized_Reference.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
100
101
        return $this->_cmsContentParameter;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    protected function redirectTo($object)
108
    {
109
        $request = $this->getRequest();
110
111
        $url = $backToNodeList = false;
112
        $instanceAdmin = $this->admin->getConfigurationPool()->getInstance('alpixel_cms.admin.block');
113
114 View Code Duplication
        if (null !== $request->get('btn_update_and_list') || null !== $request->get('btn_create_and_list')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
115
            $backToNodeList = true;
116
        }
117
118 View Code Duplication
        if (null !== $request->get('btn_create_and_create')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
            $params = [];
120
            if ($this->admin->hasActiveSubClass()) {
121
                $params['subclass'] = $request->get('subclass');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $params['subclass'] is correct as $request->get('subclass') (which targets Symfony\Component\HttpFoundation\Request::get()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
122
            }
123
            $url = $this->admin->generateUrl('create', $params);
124
        }
125
126
        if ($this->getRestMethod() === 'DELETE') {
127
            $backToNodeList = true;
128
        }
129
130 View Code Duplication
        if (!$url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
            foreach (['edit', 'show'] as $route) {
132
                if ($this->admin->hasRoute($route) && $this->admin->isGranted(strtoupper($route), $object)) {
133
                    $url = $this->admin->generateObjectUrl($route, $object);
134
                    break;
135
                }
136
            }
137
        }
138
139
        if ($backToNodeList || !$url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
140
            $url = $instanceAdmin->generateUrl('list');
141
        }
142
143
        return new RedirectResponse($url);
144
    }
145
}
146