Passed
Push — master ( 240c83...03f39b )
by Mathias
06:41
created

ManageController::formAction()   C

Complexity

Conditions 12
Paths 24

Size

Total Lines 113
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
eloc 61
dl 0
loc 113
ccs 0
cts 73
cp 0
rs 6.4242
c 0
b 0
f 0
cc 12
nc 24
nop 0
crap 156

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
/** ActionController of Core */
11
namespace Cv\Controller;
12
13
use Core\Repository\RepositoryService;
14
use Cv\Entity\CvInterface;
15
use Cv\Service\UploadHandler;
16
use Geo\Form\GeoSelect;
17
use Geo\Form\GeoText;
0 ignored issues
show
Bug introduced by
The type Geo\Form\GeoText was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use Interop\Container\ContainerInterface;
19
use Laminas\Form\FormElementManager\FormElementManagerV3Polyfill;
20
use Laminas\Mvc\Controller\AbstractActionController;
21
use Laminas\View\HelperPluginManager;
22
use Laminas\View\Model\JsonModel;
23
use Core\Form\SummaryFormInterface;
24
use Auth\Entity\User;
25
use Cv\Entity\Cv;
26
use Cv\Entity\Contact;
27
use PHPUnit\Util\Json;
28
29
/**
30
 * Main Action Controller for the application.
31
 * Responsible for displaying the home site.
32
 *
33
 */
34
class ManageController extends AbstractActionController
35
{
36
    private $repositories;
37
    
38
    private $formElements;
39
    
40
    private $viewHelper;
41
42
    private $uploadHandler;
43
44
    public function __construct(
45
        RepositoryService $repositories,
46
        FormElementManagerV3Polyfill $formElements,
47
        HelperPluginManager $viewHelper,
48
        UploadHandler $uploadHandler
49
    )
50
    {
51
        $this->repositories = $repositories;
52
        $this->formElements = $formElements;
53
        $this->viewHelper = $viewHelper;
54
        $this->uploadHandler = $uploadHandler;
55
    }
56
57
    public static function factory(ContainerInterface $container)
58
    {
59
        $repositories = $container->get('repositories');
60
        $formElements = $container->get('FormElementManager');
61
        $viewHelper = $container->get('ViewHelperManager');
62
        $uploadHandler = $container->get(UploadHandler::class);
63
64
        return new self($repositories, $formElements, $viewHelper, $uploadHandler);
65
    }
66
67
    public function formAction()
68
    {
69
        $repositories = $this->repositories;
70
        /* @var $cvRepository \Cv\Repository\Cv */
71
        $cvRepository = $repositories->get('Cv/Cv');
72
        $user = $this->auth()->getUser();
0 ignored issues
show
Bug introduced by
The method getUser() does not exist on Laminas\Stdlib\DispatchableInterface. It seems like you code against a sub-type of Laminas\Stdlib\DispatchableInterface such as Laminas\Mvc\Controller\AbstractController. ( Ignorable by Annotation )

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

72
        $user = $this->auth()->/** @scrutinizer ignore-call */ getUser();
Loading history...
Bug introduced by
The method auth() does not exist on Cv\Controller\ManageController. 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

72
        $user = $this->/** @scrutinizer ignore-call */ auth()->getUser();
Loading history...
73
        /* @var $cv Cv */
74
        $cv = $this->getCv($cvRepository, $user);
75
        $params = $this->params();
76
        
77
        if (empty($cv)) {
78
            // create draft CV
79
            $cv = $cvRepository->create();
80
            $cv->setIsDraft(true);
81
            $cv->setContact($user->getRole() == User::ROLE_USER ? $user->getInfo() : new Contact());
82
            $cv->setUser($user);
83
            $repositories->store($cv);
84
        }
85
        
86
        if (($status = $params->fromQuery('status')) != '') {
87
            $this->acl('Cv/Status', 'change');
0 ignored issues
show
Bug introduced by
The method acl() does not exist on Cv\Controller\ManageController. 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

87
            $this->/** @scrutinizer ignore-call */ 
88
                   acl('Cv/Status', 'change');
Loading history...
88
            return $this->changeStatus($cv, $status);
89
        }
90
        
91
        /* @var $container \Core\Form\Container */
92
        $container = $this->formElements
93
            ->get('CvContainer')
94
            ->setEntity($cv);
95
96
        // process post method
97
        if ($this->getRequest()->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

97
        if ($this->getRequest()->/** @scrutinizer ignore-call */ isPost()) {
Loading history...
98
            $form = $container->getForm($params->fromQuery('form'));
99
100
            if ($form) {
101
                $form->setData(array_merge(
102
                    $params->fromPost(),
103
                    $params->fromFiles()
0 ignored issues
show
Bug introduced by
It seems like $params->fromFiles() 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

103
                    /** @scrutinizer ignore-type */ $params->fromFiles()
Loading history...
104
                ));
105
                $formId = $params->fromQuery('form');
106
                $viewHelperManager = $this->viewHelper;
107
                $uploadHandler = $this->uploadHandler;
108
109
                if('image' === $formId){
110
                    // handles image upload
111
                    $uploadHandler->handleImageUpload($cv, $_FILES['image']);
112
                }
113
                elseif('attachments' === $formId){
114
                    // handles attachment upload
115
                    $attachment = $uploadHandler->handleAttachmentUpload($cv, $_FILES['attachments']);
116
                    $content = $viewHelperManager->get('basepath')
117
                        ->__invoke($attachment->getUri());
118
                    return new JsonModel([
119
                        'valid' => true,
120
                        'content' => $content,
121
                    ]);
122
                }
123
                else{
124
                    if (!$form->isValid()) {
125
                        return new JsonModel([
126
                            'valid' => false,
127
                            'errors' => $form->getMessages()
128
                        ]);
129
                    };
130
131
                    /*
132
 * @todo This is a workaround for GeoJSON data insertion
133
 * until we figured out, what we really want it to be.
134
 */
135
136
//                if ('preferredJob' == $formId) {
137
//                    $locElem = $form->getBaseFieldset()->get('geo-location');
138
//                    if ($locElem instanceof GeoText) {
139
//                        $loc = $locElem->getValue('entity');
140
//                        $locations = $cv->getPreferredJob()->getDesiredLocations();
141
//                        if (count($locations)) {
142
//                            $locations->clear();
143
//                        }
144
//                        $locations->add($loc);
145
//                        $cv->getPreferredJob()->setDesiredLocation($locElem->getValue());
146
//                    }
147
//                }
148
                    $this->validateCv($cv);
149
                    $repositories->store($cv);
150
                }
151
152
                if ('file-uri' === $params->fromPost('return')) {
153
                    $content = $viewHelperManager->get('basepath')
154
                        ->__invoke($form->getHydrator()->getLastUploadedFile()->getUri());
0 ignored issues
show
Bug introduced by
The method getLastUploadedFile() does not exist on Laminas\Hydrator\HydratorInterface. It seems like you code against a sub-type of Laminas\Hydrator\HydratorInterface such as Core\Entity\Hydrator\FileCollectionUploadHydrator. ( Ignorable by Annotation )

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

154
                        ->__invoke($form->getHydrator()->/** @scrutinizer ignore-call */ getLastUploadedFile()->getUri());
Loading history...
Bug introduced by
The method getHydrator() does not exist on Core\Form\Container. ( Ignorable by Annotation )

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

154
                        ->__invoke($form->/** @scrutinizer ignore-call */ getHydrator()->getLastUploadedFile()->getUri());

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...
155
                } else {
156
                    if ($form instanceof SummaryFormInterface) {
157
                        $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY);
158
                        $viewHelper = 'summaryForm';
159
                    } else {
160
                        $viewHelper = 'form';
161
                    }
162
                    
163
                    // render form
164
                    $content = $viewHelperManager->get($viewHelper)
165
                        ->__invoke($form);
166
                }
167
                
168
                return new JsonModel([
169
                    'valid' => true,
170
                    'content' => $content
171
                ]);
172
            } elseif (($action = $params->fromQuery('action')) !== null) {
173
                return new JsonModel($container->executeAction($action, $params->fromPost()));
174
            }
175
        }// end of process post method
176
177
        return [
178
            'container' => $container,
179
            'cv' => $cv
180
        ];
181
    }
182
183
    /**
184
     *
185
     * @param Cv $cv
186
     * @param string $status
187
     * @return \Laminas\Http\Response
188
     */
189
    protected function changeStatus(Cv $cv, $status)
190
    {
191
        if ($status != $cv->getStatus()) {
0 ignored issues
show
introduced by
The condition $status != $cv->getStatus() is always true.
Loading history...
192
            try {
193
                $cv->setStatus($status);
194
                
195
                $this->notification()->success(
0 ignored issues
show
Bug introduced by
The method success() does not exist on Laminas\Stdlib\DispatchableInterface. It seems like you code against a sub-type of Laminas\Stdlib\DispatchableInterface such as Laminas\Mvc\Controller\AbstractController. ( Ignorable by Annotation )

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

195
                $this->notification()->/** @scrutinizer ignore-call */ success(
Loading history...
Bug introduced by
The method notification() does not exist on Cv\Controller\ManageController. 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

195
                $this->/** @scrutinizer ignore-call */ 
196
                       notification()->success(
Loading history...
196
                    /*@translate*/ 'Status has been successfully changed'
197
                );
198
            } catch (\DomainException $e) {
199
                $this->notification()->error(
0 ignored issues
show
Bug introduced by
The method error() does not exist on Laminas\Stdlib\DispatchableInterface. It seems like you code against a sub-type of Laminas\Stdlib\DispatchableInterface such as Laminas\Mvc\Controller\AbstractController. ( Ignorable by Annotation )

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

199
                $this->notification()->/** @scrutinizer ignore-call */ error(
Loading history...
200
                    /*@translate*/ 'Invalid status'
201
                );
202
            }
203
        }
204
        
205
        return $this->redirect()->refresh();
206
    }
207
208
    private function getCv($repository, $user)
209
    {
210
        $id =
211
            $this->params()->fromRoute('id')
212
            ?: (
213
                $this->params()->fromQuery('id')
214
                ?: (
215
                    $this->params()->fromPost('cv')
216
                    ?: null
217
                )
218
            );
219
220
        if ('__my__' == $id) {
221
            return $repository->findOneBy(['user' => $user->getId(), 'isDraft' => null]);
222
        }
223
224
        return $id ? $repository->find($id) : $repository->findDraft($user);
225
    }
226
227
    private function validateCv(Cv $cv)
228
    {
229
        if ($cv->getContact()->getEmail()
230
            && $cv->getPreferredJob()->getDesiredJob()
231
            && count($cv->getPreferredJob()->getDesiredLocations())
232
        ) {
233
            $cv->setIsDraft(false);
234
        }
235
    }
236
}
237