Completed
Push — develop ( c603db...77b219 )
by
unknown
16:24 queued 08:23
created

UsersController::editAction()   C

Complexity

Conditions 10
Paths 20

Size

Total Lines 74
Code Lines 47

Duplication

Lines 11
Ratio 14.86 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 11
loc 74
rs 5.8102
cc 10
eloc 47
nc 20
nop 0

How to fix   Long Method    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
 * 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\View\Model\ViewModel;
15
use Zend\View\Model\JsonModel;
16
use Auth\Repository\User as UserRepository;
17
use Core\Form\SummaryFormInterface;
18
19
/**
20
 * List registered users
21
 */
22
class UsersController extends AbstractActionController
23
{
24
25
    /**
26
     * @var UserRepository
27
     */
28
    protected $userRepository;
29
30
    /**
31
     * @param UserRepository $userRepository
32
     */
33
    public function __construct(UserRepository $userRepository)
34
    {
35
        $this->userRepository = $userRepository;
36
    }
37
    
38
    /**
39
     * Login with username and password
40
     *
41
     * @return \Zend\Http\Response|ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be array?

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...
42
     */
43
    public function listAction()
44
    {
45
        /* @var \Zend\Http\Request $request */
46
        $request          = $this->getRequest();
47
        $params           = $request->getQuery();
48
49
        $paginator = $this->paginator('Auth/User', $params);
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...
50
        $form = $this->getServiceLocator()->get('forms')
51
                ->get('Core/TextSearch', [
52
                                           'placeholder' => /*@translate*/ 'Type name, email address, role, or login name',
53
                                           'button_element' => 'text'
54
                                       ]);
55
56
        $return = array(
57
            'by' => $params['by'],
58
            'users' => $paginator,
59
            'form' => $form,
60
        );
61
62
        return $return;
63
    }
64
65
    /**
66
     * Edit user
67
     *
68
     * @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...
69
     */
70
    public function editAction()
71
    {
72
        /* @var $user \Auth\Entity\User */
73
        $user = $this->userRepository->find($this->params('id'), \Doctrine\ODM\MongoDB\LockMode::NONE, null, ['allowDeactivated' => true]);
74
        
75
        // check if user is not found
76
        if (!$user) {
77
            return $this->notFoundAction();
78
        }
79
        
80
        $params = $this->params();
81
        $serviceLocator = $this->getServiceLocator();
82
        $forms = $serviceLocator->get('forms');
83
        /* @var $infoContainer \Auth\Form\UserProfileContainer */
84
        $infoContainer = $forms->get('Auth/userprofilecontainer');
85
        $infoContainer->setEntity($user);
86
        $statusContainer = $forms->get('Auth/UserStatusContainer');
87
        $statusContainer->setEntity($user);
88
        
89
        // set selected user to image strategy
90
        $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...
91
            ->getHydrator()
92
            ->getStrategy('image');
93
		$fileEntity = $imageStrategy->getFileEntity();
94
		$fileEntity->setUser($user);
95
		$imageStrategy->setFileEntity($fileEntity);
96
        
97
        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...
98
            $formName = $params->fromQuery('form');
99
            $container = $formName === 'status' ? $statusContainer : $infoContainer;
100
            $form = $container->getForm($formName);
101
        
102
            if ($form) {
103
                $postData  = $form->getOption('use_post_array') ? $params->fromPost() : [];
104
                $filesData = $form->getOption('use_files_array') ? $params->fromFiles() : [];
105
                $form->setData(array_merge($postData, $filesData));
106
        
107
                if (!$form->isValid()) {
108
                    return new JsonModel(
109
                        array(
110
                            'valid' => false,
111
                            'errors' => $form->getMessages(),
112
                        )
113
                    );
114
                }
115
                
116
                $serviceLocator->get('repositories')->store($user);
117
        
118 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...
119
                    $content = $form->getHydrator()->getLastUploadedFile()->getUri();
120
                } else {
121
                    if ($form instanceof SummaryFormInterface) {
122
                        $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY);
123
                        $viewHelper = 'summaryform';
124
                    } else {
125
                        $viewHelper = 'form';
126
                    }
127
                    $content = $serviceLocator->get('ViewHelperManager')->get($viewHelper)->__invoke($form);
128
                }
129
        
130
                return new JsonModel(
131
                    array(
132
                        'valid' => $form->isValid(),
133
                        'content' => $content,
134
                    )
135
                );
136
            }
137
        }
138
        
139
        return [
140
            'infoContainer' => $infoContainer,
141
            'statusContainer' => $statusContainer
142
        ];
143
    }
144
}
145