Completed
Push — develop ( 4bf430...c74260 )
by
unknown
18:30
created

UsersController   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 156
Duplicated Lines 16.67 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 7
dl 26
loc 156
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A listAction() 15 15 1
C editAction() 11 74 10
B switchAction() 0 38 4

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
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** Auth controller */
11
namespace Auth\Controller;
12
13
use Zend\Mvc\Controller\AbstractActionController;
14
use Zend\Session\Container;
15
use Zend\View\Model\ViewModel;
16
use Zend\View\Model\JsonModel;
17
use Auth\Repository\User as UserRepository;
18
use Core\Form\SummaryFormInterface;
19
20
/**
21
 * List registered users
22
 *
23
 * @method \Core\Controller\Plugin\CreatePaginator pagination()
24
 */
25
class UsersController extends AbstractActionController
26
{
27
28
    /**
29
     * @var UserRepository
30
     */
31
    protected $userRepository;
32
33
    /**
34
     * @param UserRepository $userRepository
35
     */
36
    public function __construct(UserRepository $userRepository)
37
    {
38
        $this->userRepository = $userRepository;
39
    }
40
    
41
    /**
42
     * List users
43
     *
44
     * @return \Zend\Http\Response|ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be \Core\Controller\Plugin\CreatePaginator?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
45
     */
46 View Code Duplication
    public function listAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
47
    {
48
        return $this->pagination([
0 ignored issues
show
Unused Code introduced by
The call to UsersController::pagination() has too many arguments starting with array('paginator' => arr...ext'), 'as' => 'form')).

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...
49
            'paginator' => ['Auth/User', 'as' => 'users'],
50
            'form' => [
51
                'Core/Search',
52
                [
53
                    'text_name' => 'text',
54
                    'text_placeholder' => /*@translate*/ 'Type name, email address, role, or login name',
55
                    'button_element' => 'text',
56
                ],
57
                'as' => 'form'
58
            ],
59
        ]);
60
    }
61
62
    /**
63
     * Edit user
64
     *
65
     * @return \Zend\Http\Response|ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be array|JsonModel?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
66
     */
67
    public function editAction()
68
    {
69
        /* @var $user \Auth\Entity\User */
70
        $user = $this->userRepository->find($this->params('id'), \Doctrine\ODM\MongoDB\LockMode::NONE, null, ['allowDeactivated' => true]);
71
        
72
        // check if user is not found
73
        if (!$user) {
74
            return $this->notFoundAction();
75
        }
76
        
77
        $params = $this->params();
78
        $serviceLocator = $this->serviceLocator;
79
        $forms = $serviceLocator->get('forms');
80
        /* @var $infoContainer \Auth\Form\UserProfileContainer */
81
        $infoContainer = $forms->get('Auth/userprofilecontainer');
82
        $infoContainer->setEntity($user);
83
        $statusContainer = $forms->get('Auth/UserStatusContainer');
84
        $statusContainer->setEntity($user);
85
        
86
        // set selected user to image strategy
87
        $imageStrategy = $infoContainer->getForm('info.image')
0 ignored issues
show
Bug introduced by
The method getHydrator does only exist in Zend\Form\FormInterface, but not in Core\Form\Container.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
88
            ->getHydrator()
89
            ->getStrategy('image');
90
		$fileEntity = $imageStrategy->getFileEntity();
91
		$fileEntity->setUser($user);
92
		$imageStrategy->setFileEntity($fileEntity);
93
        
94
        if ($this->request->isPost()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method isPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

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...
95
            $formName = $params->fromQuery('form');
96
            $container = $formName === 'status' ? $statusContainer : $infoContainer;
97
            $form = $container->getForm($formName);
98
        
99
            if ($form) {
100
                $postData  = $form->getOption('use_post_array') ? $params->fromPost() : [];
101
                $filesData = $form->getOption('use_files_array') ? $params->fromFiles() : [];
102
                $form->setData(array_merge($postData, $filesData));
103
        
104
                if (!$form->isValid()) {
105
                    return new JsonModel(
106
                        array(
107
                            'valid' => false,
108
                            'errors' => $form->getMessages(),
109
                        )
110
                    );
111
                }
112
                
113
                $serviceLocator->get('repositories')->store($user);
114
        
115 View Code Duplication
                if ('file-uri' === $params->fromPost('return')) {
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...
116
                    $content = $form->getHydrator()->getLastUploadedFile()->getUri();
117
                } else {
118
                    if ($form instanceof SummaryFormInterface) {
119
                        $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY);
120
                        $viewHelper = 'summaryform';
121
                    } else {
122
                        $viewHelper = 'form';
123
                    }
124
                    $content = $serviceLocator->get('ViewHelperManager')->get($viewHelper)->__invoke($form);
125
                }
126
        
127
                return new JsonModel(
128
                    array(
129
                        'valid' => $form->isValid(),
130
                        'content' => $content,
131
                    )
132
                );
133
            }
134
        }
135
        
136
        return [
137
            'infoContainer' => $infoContainer,
138
            'statusContainer' => $statusContainer
139
        ];
140
    }
141
142
    public function switchAction()
143
    {
144
        /* @var \Auth\Controller\Plugin\UserSwitcher $switcher */
145
        $do = $this->params()->fromQuery('do');
146
        if ('clear' == $do) {
147
            $switcher = $this->plugin('Auth/User/Switcher');
148
            $success  = $switcher();
149
150
            return new JsonModel(['success' => $success]);
151
        }
152
153
        $this->acl('Auth/Users', 'admin-access');
0 ignored issues
show
Documentation Bug introduced by
The method acl does not exist on object<Auth\Controller\UsersController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
154
155
        if ('list' == $do) {
156
            /* @var \Auth\Entity\User $user */
157
            /* @var \Zend\Paginator\Paginator $paginator */
158
            $paginator = $this->paginator('Auth/User', ['page' => 1]);
0 ignored issues
show
Documentation Bug introduced by
The method paginator does not exist on object<Auth\Controller\UsersController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
159
            $result = [];
160
161
            foreach ($paginator as $user) {
162
                $result[] = [
163
                    'id' => $user->getId(),
164
                    'name' => $user->getInfo()->getDisplayName(false),
165
                    'email' => $user->getInfo()->getEmail(),
166
                    'login' => $user->getLogin()
167
                ];
168
            }
169
            return new JsonModel([
170
                'items' => $result,
171
                'total' => $paginator->getTotalItemCount(),
172
            ]);
173
        }
174
175
        $switcher = $this->plugin('Auth/User/Switcher');
176
        $success  = $switcher($this->params()->fromQuery('id'));
0 ignored issues
show
Unused Code introduced by
$success is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
177
178
        return new JsonModel(['success' => true]);
179
    }
180
}
181