Completed
Push — develop ( e649e8...88dc2a )
by
unknown
08:28
created

IndexController::editAction()   D

Complexity

Conditions 17
Paths 42

Size

Total Lines 99
Code Lines 59

Duplication

Lines 10
Ratio 10.1 %
Metric Value
dl 10
loc 99
rs 4.8361
cc 17
eloc 59
nc 42
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   GPLv3
8
 */
9
10
/** ActionController of Organizations */
11
namespace Organizations\Controller;
12
13
use Auth\Exception\UnauthorizedAccessException;
14
use Core\Entity\Collection\ArrayCollection;
15
use Core\Form\SummaryForm;
16
use Zend\Mvc\Controller\AbstractActionController;
17
use Organizations\Repository;
18
use Organizations\Form;
19
use Zend\Session\Container as Session;
20
use Zend\View\Model\JsonModel;
21
use Core\Entity\PermissionsInterface;
22
use Zend\View\Model\ViewModel;
23
24
/**
25
 * Main Action Controller for the Organization.
26
 * Responsible for handling the organization form.
27
 *
28
 * @author Mathias Weitz <[email protected]>
29
 * @author Carsten Bleek <[email protected]>
30
 * @author Rafal Ksiazek
31
 * @author Mathias Gelhausen <[email protected]>
32
 *
33
 * @method \Acl\Controller\Plugin\Acl acl()
34
 * @method \Core\Controller\Plugin\PaginationParams paginationParams()
35
 * @method \Core\Controller\Plugin\CreatePaginator paginator(string $repositoryName, array $defaultParams = array(), bool $usePostParams = false)
36
 * @method \Auth\Controller\Plugin\Auth auth()
37
 */
38
class IndexController extends AbstractActionController
39
{
40
    /**
41
     * The organization form.
42
     *
43
     * @var Form\Organizations
44
     */
45
    private $form;
46
47
    /**
48
     * The organization repository.
49
     *
50
     * @var Repository\Organization
51
     */
52
    private $repository;
53
54
    /**
55
     * Creates an instance.
56
     *
57
     * @param Form\Organizations      $form         Organization form.
58
     * @param Repository\Organization $repository   Organization repository
59
     */
60
    public function __construct(Form\Organizations $form, Repository\Organization $repository)
61
    {
62
        $this->repository = $repository;
63
        $this->form = $form;
64
    }
65
66
    /**
67
     * attaches further Listeners for generating / processing the output
68
     *
69
     * @return $this
70
     */
71 View Code Duplication
    public function attachDefaultListeners()
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...
72
    {
73
        parent::attachDefaultListeners();
74
75
        $serviceLocator  = $this->getServiceLocator();
76
        $defaultServices = $serviceLocator->get('DefaultListeners');
77
        $events          = $this->getEventManager();
78
79
        $events->attach($defaultServices);
0 ignored issues
show
Documentation introduced by
$defaultServices is of type object|array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
80
        return $this;
81
    }
82
83
    /**
84
     * Generates a list of organizations
85
     *
86
     * @return array
87
     */
88 View Code Duplication
    public function indexAction()
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...
89
    {
90
        /* @var $request \Zend\Http\Request */
91
        $request       = $this->getRequest();
92
        $params        = $request->getQuery();
93
        $isRecruiter   = $this->acl()->isRole('recruiter');
94
        $params->count = 10;
0 ignored issues
show
Bug introduced by
Accessing count on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
95
        if ($isRecruiter) {
96
            $params->set('by', 'me');
97
        }
98
         //default sorting
99
        if (!isset($params['sort'])) {
100
            $params->set('sort', "-name");
101
        }
102
        // save the Params in the Session-Container
103
        $this->paginationParams()->setParams('Organizations\Index', $params);
0 ignored issues
show
Documentation introduced by
$params is of type object<Zend\Stdlib\ParametersInterface>, but the function expects a array|object<Core\Controller\Plugin\Parameters>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
104
        $paginator = $this->paginator('Organizations/Organization', $params);
0 ignored issues
show
Documentation introduced by
$params is of type object<Zend\Stdlib\ParametersInterface>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
105
        return array(
106
            'script' => 'organizations/index/list',
107
            'organizations' => $paginator
108
        );
109
    }
110
     
111
     
112
    /**
113
     * Change (Upsert) organizations
114
     *
115
     * @return JsonModel
116
     * @throws \RuntimeException
117
     */
118
    public function editAction()
119
    {
120
        /* @var $request \Zend\Http\Request */
121
        $serviceLocator  = $this->getServiceLocator();
122
        $return          = null;
123
        $request         = $this->getRequest();
124
        $params          = $this->params();
125
        $formIdentifier  = $params->fromQuery('form');
126
127
        try {
128
            /* @var $handler \Organizations\Controller\Plugin\GetOrganizationHandler */
129
            $handler = $this->plugin('Organizations/GetOrganizationHandler');
130
            $org  = $handler->process($this->params(), true);
131
        } catch (\RuntimeException $e) {
132
            return $this->getErrorViewModel('no-parent');
133
        }
134
135
        $container       = $this->getFormular($org);
136
137
        if (isset($formIdentifier) && $request->isPost()) {
138
            /* @var $form \Zend\Form\FormInterface */
139
            $postData = $this->params()->fromPost();
140
            $filesData = $this->params()->fromFiles();
141
            /* due to issues in ZF2 we need to clear the employees collection in the entity,
142
             * prior to binding. Otherwise it is not possible to REMOVE an employee, as the
143
             * MultiCheckbox Validation will FAIL on empty values!
144
             */
145
            if ("employeesManagement" == $formIdentifier) {
146
                $markedEmps = array();
147
                // Check if no permissions are set, and set one, mark this employee and restore it afterwards.
148
                foreach ($postData['employees']['employees'] as &$empData) {
149
                    if (!isset($empData['permissions'])) {
150
                        $empData['permissions'][] = 16;
151
                        $markedEmps[] = $empData['user'];
152
                    }
153
                }
154
                $org->setEmployees(new ArrayCollection());
155
            }
156
157
            $form = $container->get($formIdentifier);
158
            $form->setData(array_merge($postData, $filesData));
159
            if (!isset($form)) {
160
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
161
            }
162
            $isValid = $form->isValid();
163
164
            if ("employeesManagement" == $formIdentifier) {
165
                // remove permissions from marked employees
166
                foreach ($org->getEmployees() as $emp) {
167
                    $empId = $emp->getUser()->getId();
168
                    if (in_array($empId, $markedEmps)) {
0 ignored issues
show
Bug introduced by
The variable $markedEmps 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...
169
                        $emp->getPermissions()->revokeAll();
170
                    }
171
                }
172
            }
173
            if ($isValid) {
174
                $orgName = $org->getOrganizationName();
175
                if ($orgName && '' !== (string) $orgName->getName()) {
176
                    $org->setIsDraft(false);
177
                }
178
                $serviceLocator->get('repositories')->persist($org);
179
            }
180
181
            $organization = $container->getEntity();
182
            $serviceLocator->get('repositories')->store($organization);
183
184
            if ('file-uri' === $this->params()->fromPost('return')) {
185
                /* @var $hydrator \Core\Entity\Hydrator\FileCollectionUploadHydrator
186
                 * @var $file     \Organizations\Entity\OrganizationImage */
187
                $basepath = $serviceLocator->get('ViewHelperManager')->get('basepath');
188
                $hydrator = $form->getHydrator();
189
                $file     = $hydrator->getLastUploadedFile();
190
                $content = $basepath($file->getUri());
191 View Code Duplication
            } else {
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...
192
                if ($form instanceof SummaryForm) {
193
                    /* @var $form \Core\Form\SummaryForm */
194
                    $form->setRenderMode(SummaryForm::RENDER_SUMMARY);
195
                    $viewHelper = 'summaryform';
196
                } else {
197
                    $viewHelper = 'form';
198
                }
199
                $content = $serviceLocator->get('ViewHelperManager')->get($viewHelper)->__invoke($form);
200
            }
201
202
            return new JsonModel(
203
                array(
204
                'valid' => $isValid,
205
                'content' => $content,
206
                )
207
            );
208
        }
209
210
        if (!isset($return)) {
211
            $return = array(
212
                'form' => $container
213
            );
214
        }
215
        return $return;
216
    }
217
218
    /**
219
     * Gets the organization form container.
220
     *
221
     * @param \Organizations\Entity\OrganizationInterface $organization
222
     *
223
     * @return \Organizations\Form\Organizations
224
     */
225
    protected function getFormular($organization)
226
    {
227
        /* @var $container \Organizations\Form\Organizations */
228
        $services  = $this->getServiceLocator();
229
        $forms     = $services->get('FormElementManager');
230
        $container = $forms->get(
231
            'organizations/form',
232
            array(
233
            'mode' => $organization->getId() ? 'edit' : 'new'
234
            )
235
        );
236
        $container->setEntity($organization);
237
        $container->setParam('id', $organization->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Organizations\Entity\OrganizationInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
238
//        $container->setParam('applyId',$job->applyId);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
239
240
        if ('__my__' != $this->params('id', '')) {
241
            $container->disableForm('employeesManagement')
242
                        ->disableForm('workflowSettings');
243
        } else {
244
            $container ->disableForm('organizationLogo')
245
                        ->disableForm('descriptionForm');
246
        }
247
        return $container;
248
    }
249
250
    protected function getErrorViewModel($script)
251
    {
252
        $this->getResponse()->setStatusCode(500);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\ResponseInterface as the method setStatusCode() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Response, Zend\Http\Response, Zend\Http\Response\Stream.

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...
253
254
        $model = new ViewModel();
255
        $model->setTemplate("organizations/error/$script");
256
257
        return $model;
258
    }
259
}
260