AdminNodeController   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 146
Duplicated Lines 16.44 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 31
lcom 1
cbo 9
dl 24
loc 146
rs 9.92
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A forwardEditAction() 0 22 3
A createTranslationAction() 0 23 4
B seeAction() 0 22 6
A listAction() 0 24 3
C redirectTo() 24 45 15

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Alpixel\Bundle\CMSBundle\Controller;
4
5
use Sonata\AdminBundle\Controller\CRUDController as Controller;
6
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
7
use Symfony\Component\HttpFoundation\RedirectResponse;
8
use Symfony\Component\HttpFoundation\Request;
9
10
class AdminNodeController extends Controller
11
{
12
    public function forwardEditAction(Request $request)
13
    {
14
        $entityManager = $this->get('doctrine.orm.entity_manager');
15
16
        $node = $entityManager->getRepository('AlpixelCMSBundle:Node')
17
            ->find($request->get('id'));
18
19
        // Forward edit action from EN page set locale for admin to EN instead default locale
20
        $defaultLocale = $this->getParameter('default_locale');
21
        $request->setLocale($defaultLocale);
22
23
        if ($node !== null) {
24
            $instanceAdmin = $this->admin->getConfigurationPool()->getAdminByClass(get_class($node));
25
            if ($instanceAdmin !== null) {
26
                return $this->redirect($instanceAdmin->generateUrl('edit', ['id' => $request->get('id')]));
27
            }
28
        }
29
30
        $instanceAdmin = $this->admin->getConfigurationPool()->getInstance('alpixel_cms.admin.node');
31
32
        return $this->redirect($instanceAdmin->generateUrl('list'));
33
    }
34
35
    public function createTranslationAction(Request $request)
36
    {
37
        $object = $this->admin->getSubject();
38
        $locale = $request->query->get('locale');
39
40
        if ($locale === null || $object === null) {
41
            return $this->createNotFoundException();
42
        }
43
44
        $entityManager = $this->get('doctrine.orm.entity_manager');
45
        $translation = $entityManager->getRepository('AlpixelCMSBundle:Node')
46
            ->findTranslation($object, $locale);
47
48
        if ($translation !== null) {
49
            return $this->redirect($this->admin->generateUrl('edit', ['id' => $translation->getId()]));
50
        } else {
51
            $translatedContent = $this->get('alpixel_cms.helper.cms')->createTranslation($object, $locale);
52
            $entityManager->persist($translatedContent);
53
            $entityManager->flush();
54
55
            return $this->redirect($this->admin->generateUrl('edit', ['id' => $translatedContent->getId()]));
56
        }
57
    }
58
59
    public function seeAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
60
    {
61
        $object = $this->admin->getSubject();
62
        $contentTypes = $this->admin->getCMSTypes();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Sonata\AdminBundle\Admin\AdminInterface as the method getCMSTypes() does only exist in the following implementations of said interface: Alpixel\Bundle\CMSBundle\Admin\AdminBlock, Alpixel\Bundle\CMSBundle\Admin\AdminNode, Alpixel\Bundle\CMSBundle\Admin\BaseAdmin, Alpixel\Bundle\CMSBundle...in\BaseBlockEntityAdmin, Alpixel\Bundle\CMSBundle\Admin\BaseNodeEntityAdmin.

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...
63
64
        foreach ($contentTypes as $key => $contentType) {
65
            if ($key === $object->getType()) {
66
                if (isset($contentType['controller'])) {
67
                    return $this->redirectToRoute('alpixel_cms', [
68
                        'slug'    => $object->getSlug(),
69
                        '_locale' => $object->getLocale(),
70
                    ]);
71
                } elseif ($contentType['admin'] !== null && $contentType['admin']->showCustomURL($object) !== null) {
72
                    return $this->redirect($contentType['admin']->showCustomURL($object));
73
                }
74
            }
75
        }
76
77
        $this->get('session')->getFlashBag()->add('warning', 'Impossible de trouver une adresse pour cette page');
78
79
        return $this->redirectTo($object);
80
    }
81
82
    public function listAction(Request $request = null)
83
    {
84
        if (false === $this->admin->isGranted('LIST')) {
85
            throw new AccessDeniedException("You can't access the list view");
86
        }
87
88
        $datagrid = $this->admin->getDatagrid();
89
        $formView = $datagrid->getForm()->createView();
90
91
        if (!$this->container->hasParameter('alpixel_cms.content_types')) {
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 hasParameter() 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...
92
            throw $this->createNotFoundException('alpixel_cms.content_types parameters has not been  not found, maybe you must be configured cms.yml file');
93
        }
94
95
        $cmsContentType = $this->container->getParameter('alpixel_cms.content_types');
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...
96
        $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
97
98
        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...
99
            'action'         => 'list',
100
            'cmsContentType' => $cmsContentType,
101
            'form'           => $formView,
102
            'datagrid'       => $datagrid,
103
            'csrf_token'     => $this->getCsrfToken('sonata.batch'),
104
        ], null, $request);
0 ignored issues
show
Unused Code introduced by
The call to AdminNodeController::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...
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110
    protected function redirectTo($object)
111
    {
112
        $request = $this->getRequest();
113
114
        $url = $backToNodeList = false;
115
        $instanceAdmin = $this->admin->getConfigurationPool()->getInstance('alpixel_cms.admin.node');
116
117 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...
118
            $backToNodeList = true;
119
        }
120
121 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...
122
            $params = [];
123
            if ($this->admin->hasActiveSubClass()) {
124
                $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...
125
            }
126
            $url = $this->admin->generateUrl('create', $params);
127
        }
128
129 View Code Duplication
        if (null !== $request->get('btn_update_and_see_page') || null !== $request->get('btn_create_and_see_page')) {
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...
130
            return $this->redirectToRoute('alpixel_cms', [
131
                'slug'    => $object->getSlug(),
132
                '_locale' => $object->getLocale(),
133
            ]);
134
        }
135
136
        if ($this->getRestMethod() === 'DELETE') {
137
            $backToNodeList = true;
138
        }
139
140 View Code Duplication
        if (!$url && !$backToNodeList) {
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...
141
            foreach (['edit', 'show'] as $route) {
142
                if ($this->admin->hasRoute($route) && $this->admin->isGranted(strtoupper($route), $object)) {
143
                    $url = $this->admin->generateObjectUrl($route, $object);
144
                    break;
145
                }
146
            }
147
        }
148
149
        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...
150
            $url = $instanceAdmin->generateUrl('list');
151
        }
152
153
        return new RedirectResponse($url);
154
    }
155
}
156