IndexController::editAction()   D
last analyzed

Complexity

Conditions 20
Paths 46

Size

Total Lines 113
Code Lines 66

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 420

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 66
dl 0
loc 113
ccs 0
cts 57
cp 0
rs 4.1666
c 1
b 1
f 0
cc 20
nc 46
nop 0
crap 420

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 https://yawik.org/COPYRIGHT.php
7
 * @license   GPLv3
8
 */
9
10
/** ActionController of Organizations */
11
namespace Organizations\Controller;
12
13
use Core\Entity\Collection\ArrayCollection;
14
use Core\Form\Form as CoreForm;
15
use Core\Form\SummaryForm;
16
use Organizations\Entity\OrganizationInterface;
17
use Organizations\Exception\MissingParentOrganizationException;
18
use Laminas\Form\FormElementManager;
19
use Laminas\I18n\Translator\TranslatorInterface;
20
use Laminas\Mvc\Controller\AbstractActionController;
21
use Organizations\Repository;
22
use Organizations\Form;
23
use Laminas\Mvc\I18n\Translator;
24
use Laminas\View\Model\JsonModel;
25
use Laminas\View\Model\ViewModel;
26
use Laminas\Http\PhpEnvironment\Response;
27
use Core\Entity\Exception\NotFoundException;
28
use Organizations\Service\UploadHandler;
29
30
/**
31
 * Main Action Controller for the Organization.
32
 * Responsible for handling the organization form.
33
 *
34
 * @author Mathias Weitz <[email protected]>
35
 * @author Carsten Bleek <[email protected]>
36
 * @author Rafal Ksiazek
37
 * @author Mathias Gelhausen <[email protected]>
38
 * @author Miroslav Fedeleš <[email protected]>
39
 * @author Anthonius Munthi <[email protected]>
40
 *
41
 * @method \Acl\Controller\Plugin\Acl acl()
42
 * @method \Core\Controller\Plugin\PaginationParams paginationParams()
43
 * @method \Core\Controller\Plugin\CreatePaginator paginator(string $repositoryName, array $defaultParams = array(), bool $usePostParams = false)
44
 * @method \Auth\Controller\Plugin\Auth auth()
45
 */
46
class IndexController extends AbstractActionController
47
{
48
    /**
49
     * The organization form.
50
     *
51
     * @var Form\Organizations
52
     */
53
    private $form;
54
55
    /**
56
     * The organization repository.
57
     *
58
     * @var Repository\Organization
59
     */
60
    private $repository;
61
62
    /**
63
     * @var FormElementManager
64
     */
65
    private $formManager;
66
67
    private $viewHelper;
68
69
    /**
70
     * @var TranslatorInterface
71
     */
72
    private $translator;
73
    /**
74
     * @var UploadHandler
75
     */
76
    private UploadHandler $manageHandler;
77
78
    /**
79
     * Create new controller instance
80 1
     *
81
     * @param Form\Organizations $form
82
     * @param Repository\Organization $repository
83
     * @param TranslatorInterface $translator
84
     * @param $formManager
85
     * @param $viewHelper
86
     * @param UploadHandler $manageHandler
87 1
     */
88 1
    public function __construct(
89 1
        Form\Organizations $form,
90 1
        Repository\Organization $repository,
91 1
        TranslatorInterface $translator,
92
        $formManager,
93
        $viewHelper,
94
        UploadHandler $manageHandler
95
    ) {
96
        $this->repository = $repository;
97
        $this->form = $form;
98
        $this->formManager = $formManager;
99
        $this->viewHelper = $viewHelper;
100
        $this->translator = $translator;
101
        $this->manageHandler = $manageHandler;
102
    }
103
104
    /**
105
     * Generates a list of organizations
106
     *
107
     * @return array
108
     */
109
    public function indexAction()
110
    {
111
        return $this->pagination([
0 ignored issues
show
Bug introduced by
The method pagination() does not exist on Organizations\Controller\IndexController. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

111
        return $this->/** @scrutinizer ignore-call */ pagination([
Loading history...
Bug Best Practice introduced by
The expression return $this->pagination...xt'), 'as' => 'form'))) also could return the type Laminas\Stdlib\DispatchableInterface which is incompatible with the documented return type array.
Loading history...
112
            'paginator' => [
113
                'Organizations/Organization',
114
                'as' => 'organizations'
115
            ],
116
            'form' => [
117
                'Core/Search',
118
                [
119
                    'text_name' => 'text',
120
                    'text_placeholder' => /*@translate*/ 'Search for organizations',
121
                    'button_element' => 'text'
122
                ],
123
                'as' => 'form'
124
            ]
125
        ]);
126
    }
127
128
    /**
129
     * Change (Upsert) organizations
130
     *
131
     * @return JsonModel|array
132
     * @throws \RuntimeException
133
     */
134
    public function editAction()
135
    {
136
        /* @var $request \Laminas\Http\Request */
137
        $translator      = $this->translator;
138
        $return          = null;
139
        $request         = $this->getRequest();
140
        $params          = $this->params();
141
        $formIdentifier  = $params->fromQuery('form');
142
143
        try {
144
            /* @var $handler \Organizations\Controller\Plugin\GetOrganizationHandler */
145
            $handler = $this->plugin('Organizations/GetOrganizationHandler');
146
            $org  = $handler->process($this->params(), true);
147
        } catch (MissingParentOrganizationException $e) {
148
            return $this->getErrorViewModel('no-parent');
149
        } catch (NotFoundException $e) {
150
            $this->getResponse()->setStatusCode(Response::STATUS_CODE_404);
0 ignored issues
show
Bug introduced by
The method setStatusCode() does not exist on Laminas\Stdlib\ResponseInterface. It seems like you code against a sub-type of Laminas\Stdlib\ResponseInterface such as Laminas\Http\Response. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

150
            $this->getResponse()->/** @scrutinizer ignore-call */ setStatusCode(Response::STATUS_CODE_404);
Loading history...
151
            return [
152
                'message' => sprintf($translator->translate('Organization with id "%s" not found'), $e->getId()),
153
                'exception' => $e
154
            ];
155
        }
156
157
        $container       = $this->getFormular($org);
158
159
        if (isset($formIdentifier) && $request->isPost()) {
0 ignored issues
show
Bug introduced by
The method isPost() does not exist on Laminas\Stdlib\RequestInterface. It seems like you code against a sub-type of Laminas\Stdlib\RequestInterface such as Laminas\Http\Request. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

159
        if (isset($formIdentifier) && $request->/** @scrutinizer ignore-call */ isPost()) {
Loading history...
160
            /* @var $form \Laminas\Form\FormInterface */
161
            $postData = $this->params()->fromPost();
162
            $filesData = $this->params()->fromFiles();
163
            /* due to issues in ZF2 we need to clear the employees collection in the entity,
164
             * prior to binding. Otherwise it is not possible to REMOVE an employee, as the
165
             * MultiCheckbox Validation will FAIL on empty values!
166
             */
167
            if ("employeesManagement" == $formIdentifier) {
168
                $markedEmps = array();
169
                // Check if no permissions are set, and set one, mark this employee and restore it afterwards.
170
                foreach ($postData['employees']['employees'] as &$empData) {
171
                    if (!isset($empData['permissions'])) {
172
                        $empData['permissions'][] = 16;
173
                        $markedEmps[] = $empData['user'];
174
                    }
175
                }
176
                $org->setEmployees(new ArrayCollection());
177
            }
178
179
            $organization = $container->getEntity();
180
            $form = $container->get($formIdentifier);
181
            $form->setData(array_merge($postData, $filesData));
0 ignored issues
show
Bug introduced by
The method setData() does not exist on Laminas\Form\ElementInterface. It seems like you code against a sub-type of Laminas\Form\ElementInterface such as Laminas\Form\FormInterface or Laminas\Form\Form or Core\Form\Container or Laminas\Form\Form. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

181
            $form->/** @scrutinizer ignore-call */ 
182
                   setData(array_merge($postData, $filesData));
Loading history...
Bug introduced by
It seems like $filesData can also be of type ArrayAccess and null; however, parameter $arrays of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

181
            $form->setData(array_merge($postData, /** @scrutinizer ignore-type */ $filesData));
Loading history...
182
            if (!isset($form)) {
183
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
184
            }
185
186
            if('organizationLogo' == $formIdentifier){
187
                return $this->handleLogoUpload($form, $filesData);
0 ignored issues
show
Bug introduced by
It seems like $filesData can also be of type ArrayAccess and null; however, parameter $filesData of Organizations\Controller...ler::handleLogoUpload() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

187
                return $this->handleLogoUpload($form, /** @scrutinizer ignore-type */ $filesData);
Loading history...
188
            }
189
190
            $isValid = $form->isValid();
0 ignored issues
show
Bug introduced by
The method isValid() does not exist on Laminas\Form\ElementInterface. It seems like you code against a sub-type of Laminas\Form\ElementInterface such as Laminas\Form\FormInterface or Laminas\Form\Form or Core\Form\Container or Laminas\Form\Form. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

190
            /** @scrutinizer ignore-call */ 
191
            $isValid = $form->isValid();
Loading history...
191
192
            if ("employeesManagement" == $formIdentifier) {
193
                // remove permissions from marked employees
194
                foreach ($org->getEmployees() as $emp) {
195
                    $empId = $emp->getUser()->getId();
196
                    if (in_array($empId, $markedEmps)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $markedEmps does not seem to be defined for all execution paths leading up to this point.
Loading history...
197
                        $emp->getPermissions()->revokeAll();
198
                    }
199
                }
200
            }
201
202
            if ($isValid) {
203
                $orgName = $org->getOrganizationName();
204
                if ($orgName && '' !== (string) $orgName->getName()) {
205
                    $org->setIsDraft(false);
206
                }
207
                $this->repository->store($org);
208
            }
209
210
211
            $this->repository->store($organization);
212
213
            if ('file-uri' === $this->params()->fromPost('return')) {
214
                /* @var $hydrator \Core\Entity\Hydrator\FileCollectionUploadHydrator
215
                 * @var $file     \Organizations\Entity\OrganizationImage */
216
                $basepath = $this->viewHelper->get('basepath');
217
                $hydrator = $form->getHydrator();
0 ignored issues
show
Bug introduced by
The method getHydrator() does not exist on Laminas\Form\ElementInterface. It seems like you code against a sub-type of Laminas\Form\ElementInterface such as Laminas\Form\FieldsetInterface or Laminas\Form\Fieldset. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

217
                /** @scrutinizer ignore-call */ 
218
                $hydrator = $form->getHydrator();
Loading history...
218
                $file     = $hydrator->getLastUploadedFile();
219
                $content = $basepath($file->getUri());
220
            } else {
221
                if ($form instanceof SummaryForm) {
222
                    /* @var $form \Core\Form\SummaryForm */
223
                    $form->setRenderMode($isValid ? SummaryForm::RENDER_SUMMARY : SummaryForm::RENDER_FORM);
224
                    $viewHelper = 'summaryForm';
225
                } else {
226
                    $viewHelper = 'form';
227
                }
228
229
                $content = $this->viewHelper->get($viewHelper)->__invoke($form);
230
            }
231
232
            return new JsonModel(
233
                array(
234
                'valid' => $isValid,
235
                'errors' => $form->getMessages(),
236
                'content' => $content,
237
                )
238
            );
239
        }
240
241
        if (!isset($return)) {
242
            $return = array(
243
                'form' => $container
244
            );
245
        }
246
        return $return;
247
    }
248
249
    /**
250
     * Gets the organization form container.
251
     *
252
     * @param \Organizations\Entity\OrganizationInterface $organization
253
     *
254
     * @return \Organizations\Form\Organizations
255
     */
256
    protected function getFormular($organization)
257
    {
258
        /* @var $container \Organizations\Form\Organizations */
259
        //$services  = $this->serviceLocator;
260
        $forms     = $this->formManager;
261
        $container = $forms->get(
262
            'Organizations/Form',
263
            array(
264
            'mode' => $organization->getId() ? 'edit' : 'new'
265
            )
266
        );
267
        $container->setEntity($organization);
268
        $container->setParam('id', $organization->getId());
269
//        $container->setParam('applyId',$job->applyId);
270
271
        if ('__my__' != $this->params('id', '')) {
272
            $container->disableForm('employeesManagement')
273
                        ->disableForm('workflowSettings');
274
        } else {
275
            $container ->disableForm('organizationLogo')
276
                        ->disableForm('descriptionForm');
277
        }
278
        return $container;
279
    }
280
281
    protected function getErrorViewModel($script)
282
    {
283
        $this->getResponse()->setStatusCode(Response::STATUS_CODE_500);
284
285
        $model = new ViewModel();
286
        $model->setTemplate("organizations/error/$script");
287
288
        return $model;
289
    }
290
291
    private function handleLogoUpload(CoreForm $form, array $filesData): JsonModel
292
    {
293
        $id = $this->params('id');
294
        $manageHandler = $this->manageHandler;
295
        $data = $filesData['original'];
296
        $organization = $manageHandler->handleLogoUpload($id, $data);
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type Laminas\Mvc\Controller\Plugin\Params; however, parameter $oganizationID of Organizations\Service\Up...ler::handleLogoUpload() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

296
        $organization = $manageHandler->handleLogoUpload(/** @scrutinizer ignore-type */ $id, $data);
Loading history...
297
        $form->getParent()->setEntity($organization);
0 ignored issues
show
Bug introduced by
The method setEntity() does not exist on Laminas\Form\Form. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

297
        $form->getParent()->/** @scrutinizer ignore-call */ setEntity($organization);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
298
        $content = $this->viewHelper->get('form')->__invoke($form);
299
        return new JsonModel([
300
            'valid' => true,
301
            'content' => $content
302
        ]);
303
    }
304
}
305