ManageController::save()   F
last analyzed

Complexity

Conditions 24
Paths 5383

Size

Total Lines 179
Code Lines 110

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 600

Importance

Changes 0
Metric Value
eloc 110
dl 0
loc 179
c 0
b 0
f 0
ccs 0
cts 138
cp 0
rs 0
cc 24
nc 5383
nop 0
crap 600

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
/**
4
 * YAWIK
5
 *
6
 * @filesource
7
 * @copyright https://yawik.org/COPYRIGHT.php
8
 * @license   MIT
9
 */
10
11
/** ActionController of Core */
12
namespace Jobs\Controller;
13
14
use Jobs\Entity\JobInterface;
15
use Jobs\Entity\JobSnapshot;
16
use Jobs\Entity\JobSnapshotStatus;
17
use Jobs\Entity\Status;
18
use Core\Repository\RepositoryService;
19
use Laminas\EventManager\EventInterface;
20
use Laminas\EventManager\EventManagerInterface;
21
use Laminas\Filter\FilterPluginManager;
22
use Laminas\I18n\Translator\TranslatorInterface;
23
use Laminas\Mvc\Controller\AbstractActionController;
24
use Laminas\Validator\ValidatorPluginManager;
25
use Laminas\View\HelperPluginManager;
26
use Laminas\View\Model\ViewModel;
27
use Laminas\View\Model\JsonModel;
28
use Core\Form\SummaryForm;
29
use Laminas\Mvc\MvcEvent;
30
use Jobs\Listener\Events\JobEvent;
31
use Core\Form\SummaryFormInterface;
32
use Laminas\Stdlib\ArrayUtils;
33
use Auth\AuthenticationService;
34
use Laminas\Mvc\I18n\Translator;
35
use Laminas\Http\PhpEnvironment\Response;
36
use Core\Entity\Exception\NotFoundException;
37
38
/**
39
 * This Controller handles management actions for jobs.
40
 *
41
 * @method \Acl\Controller\Plugin\Acl acl()
42
 * @method \Jobs\Controller\Plugin\InitializeJob initializeJob()
43
 * @method \Core\Controller\Plugin\Notification notification()
44
 * @method \Core\Controller\Plugin\EntitySnapshot entitySnapshot()
45
 *
46
 * @author Mathias Gelhausen <[email protected]>
47
 * @author Mathias Weitz <[email protected]>
48
 * @author Carsten Bleek <[email protected]>
49
 * @author Rafal Ksiazek
50
 * @author Miroslav Fedeleš <[email protected]>
51
 * @author Anthonius Munthi <[email protected]>
52
 */
53
class ManageController extends AbstractActionController
54
{
55
    /**
56
     * @var AuthenticationService
57
     */
58
    protected $auth;
59
60
    /**
61
     * @var RepositoryService
62
     */
63
    protected $repositoryService;
64
65
    /**
66
     * @var Translator
67
     */
68
    protected $translator;
69
70
	/**
71
	 * @var FilterPluginManager
72
	 */
73
    protected $filterManager;
74
75
    protected $jobFormEvents;
76
77
	/**
78
	 * @var
79
	 */
80
    protected $formManager;
81
82
    protected $options;
83
84
    protected $viewHelper;
85
86
    protected $validatorManager;
87
88
    protected $jobEvents;
89
90
    protected $jobEvent;
91
92
	/**
93
	 * ManageController constructor.
94
	 *
95
	 * @TODO: [ZF3] make this controller more thin, looks like so much things to do
96
	 *
97
	 * @param AuthenticationService $auth
98
	 * @param RepositoryService $repositoryService
99
	 * @param TranslatorInterface $translator
100
	 * @param FilterPluginManager $filterManager
101
	 * @param EventManagerInterface $jobFormEvents
102
	 * @param $formManager
103
	 * @param $options
104
	 * @param HelperPluginManager $viewHelper
105
	 * @param ValidatorPluginManager $validatorManager
106
	 * @param EventManagerInterface $jobEvents
107
	 * @param EventInterface $jobEvent
108
	 */
109
    public function __construct(
110
    	AuthenticationService $auth,
111
	    RepositoryService $repositoryService,
112
	    TranslatorInterface $translator,
113
		FilterPluginManager $filterManager,
114
		EventManagerInterface $jobFormEvents,
115
		$formManager,
116
		$options,
117
		HelperPluginManager $viewHelper,
118
		ValidatorPluginManager $validatorManager,
119
		EventManagerInterface $jobEvents,
120
		EventInterface $jobEvent
121
    )
122
    {
123
        $this->auth = $auth;
124
        $this->repositoryService = $repositoryService;
125
        $this->translator = $translator;
0 ignored issues
show
Documentation Bug introduced by
$translator is of type Laminas\I18n\Translator\TranslatorInterface, but the property $translator was declared to be of type Laminas\Mvc\I18n\Translator. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
126
        $this->filterManager = $filterManager;
127
        $this->jobFormEvents = $jobFormEvents;
128
        $this->formManager = $formManager;
129
        $this->options = $options;
130
        $this->viewHelper = $viewHelper;
131
        $this->validatorManager = $validatorManager;
132
        $this->jobEvents = $jobEvents;
133
        $this->jobEvent = $jobEvent;
134
    }
135
136
    /**
137
     * @return $this|void
138
     */
139
    public function attachDefaultListeners()
140
    {
141
        parent::attachDefaultListeners();
142
        $events = $this->getEventManager();
143
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
144
    }
145
146
    /**
147
     * Dispatch listener callback.
148
     *
149
     * Attaches the MailSender aggregate listener to the job event manager.
150
     *
151
     * @param MvcEvent $e
152
     * @since 0.19
153
     */
154
    public function preDispatch(MvcEvent $e)
155
    {
156
        if ('calculate' == $this->params()->fromQuery('do')) {
157
            return;
158
        }
159
        $routeMatch = $e->getRouteMatch();
160
        $action = $routeMatch->getParam('action');
161
	    $services = $e->getApplication()->getServiceManager();
162
        if (in_array($action, array('edit', 'approval', 'completion'))) {
163
            $jobEvents = $services->get('Jobs/Events');
164
            $mailSender = $services->get('Jobs/Listener/MailSender');
165
166
            $mailSender->attach($jobEvents);
167
        }
168
    }
169
170
    /**
171
     *
172
     *
173
     * @return null|ViewModel
174
     */
175
    public function editAction()
176
    {
177
        if ('calculate' == $this->params()->fromQuery('do')) {
178
            $calc = $this->filterManager->get('Jobs/ChannelPrices');
179
            $sum = $calc->filter($this->params()->fromPost('channels'));
180
181
            return new JsonModel(['sum' => $sum]);
182
        }
183
184
        return $this->save();
185
    }
186
187
    /**
188
     * @return null|ViewModel
189
     */
190
    public function saveAction()
191
    {
192
        return $this->save();
193
    }
194
195
    public function channelListAction()
196
    {
197
198
        $options = $this->options['core'];
199
        $channels = $this->options['channels'];
200
201
202
203
        $jobEntity = $this->initializeJob()->get($this->params(), true);
204
205
        $model = new ViewModel([
206
                                   'portals' => $jobEntity->getPortals(),
207
                                   'channels' => $channels,
208
                                   'defaultCurrencyCode' => $options->defaultCurrencyCode,
209
                                   'defaultTaxRate' =>  $options->defaultTaxRate,
210
                                   'jobId' => $jobEntity->getId()
211
                               ]);
212
        $model->setTemplate('jobs/partials/channel-list')->setTerminal(true);
213
        return $model;
214
    }
215
216
    /**
217
     * save a Job-Post either by a regular request or by an async post (AJAX)
218
     * a mandatory parameter is the ID of the Job
219
     * in case of a regular Request you can
220
     *
221
     * parameter are arbitrary elements for defaults or programming flow
222
     *
223
     * @param array $parameter
224
     * @return null|ViewModel
225
     * @throws \RuntimeException
226
     */
227
    protected function save()
228
    {
229
		$formEvents = $this->jobFormEvents;
230
        $user               = $this->auth->getUser();
231
        if (empty($user->getInfo()->getEmail())) {
232
            return $this->getErrorViewModel('no-parent', array('cause' => 'noEmail'));
233
        }
234
        $userOrg            = $user->getOrganization();
235
        if (!$userOrg->hasAssociation() || $userOrg->getOrganization()->isDraft()) {
0 ignored issues
show
Bug introduced by
The method isDraft() does not exist on Organizations\Entity\OrganizationInterface. It seems like you code against a sub-type of Organizations\Entity\OrganizationInterface such as Organizations\Entity\Organization. ( Ignorable by Annotation )

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

235
        if (!$userOrg->hasAssociation() || $userOrg->getOrganization()->/** @scrutinizer ignore-call */ isDraft()) {
Loading history...
236
            return $this->getErrorViewModel('no-parent', array('cause' => 'noCompany'));
237
        }
238
239
        try {
240
            $jobEntity = $this->initializeJob()->get($this->params(), true, true);
241
        } catch (NotFoundException $e) {
242
            $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

242
            $this->getResponse()->/** @scrutinizer ignore-call */ setStatusCode(Response::STATUS_CODE_404);
Loading history...
243
            return [
0 ignored issues
show
Bug Best Practice introduced by
The expression return array('message' =...()), 'exception' => $e) returns the type array<string,Core\Entity...tFoundException|string> which is incompatible with the documented return type Laminas\View\Model\ViewModel|null.
Loading history...
244
                'message' => sprintf($this->translator->translate('Job with id "%s" not found'), $e->getId()),
245
                'exception' => $e
246
            ];
247
        }
248
249
250
        /** @var \Laminas\Http\Request $request */
251
        $request            = $this->getRequest();
252
        $isAjax             = $request->isXmlHttpRequest();
253
254
        $params             = $this->params();
255
        $formIdentifier     = $params->fromQuery('form');
256
257
        if ('1' == $params->fromQuery('admin')) {
258
            /* @var \Auth\Controller\Plugin\UserSwitcher $switcher */
259
            $switcher = $this->plugin('Auth/User/Switcher');
260
            $switcher($jobEntity->getUser(), ['ref' => urldecode($params->fromQuery('return'))]);
261
        }
262
263
264
        $viewModel          = null;
265
        $this->acl($jobEntity, 'edit');
0 ignored issues
show
Unused Code introduced by
The call to Jobs\Controller\ManageController::acl() has too many arguments starting with $jobEntity. ( Ignorable by Annotation )

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

265
        $this->/** @scrutinizer ignore-call */ 
266
               acl($jobEntity, 'edit');

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. Please note the @ignore annotation hint above.

Loading history...
266
        if ($status = $params->fromQuery('status')) {
267
            $this->changeStatus($jobEntity, $status);
268
        }
269
270
        $form               = $this->getFormular($jobEntity);
271
272
        $valid              = true;
273
        $instanceForm       = null;
274
        $formErrorMessages = array();
275
276
        if (isset($formIdentifier) &&  $request->isPost()) {
277
            // at this point the form get instantiated and immediately accumulated
278
            $instanceForm = $form->getForm($formIdentifier);
279
            if (!isset($instanceForm)) {
280
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
281
            }
282
            // the id may be part of the postData, but it never should be altered
283
            $postData = $request->getPost();
284
            if (isset($postData['id'])) {
285
                unset($postData['id']);
286
            }
287
            unset($postData['applyId']);
288
            $instanceForm->setData($postData);
289
            $valid = $instanceForm->isValid();
290
            $formErrorMessages = ArrayUtils::merge($formErrorMessages, $instanceForm->getMessages());
0 ignored issues
show
Bug introduced by
It seems like $instanceForm->getMessages() can also be of type Traversable; however, parameter $b of Laminas\Stdlib\ArrayUtils::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

290
            $formErrorMessages = ArrayUtils::merge($formErrorMessages, /** @scrutinizer ignore-type */ $instanceForm->getMessages());
Loading history...
291
            if ($valid) {
292
                /*
293
                 * @todo This is a workaround for GeoJSON data insertion
294
                 * until we figured out, what we really want it to be.
295
                 */
296
//                if ('general.locationForm' == $formIdentifier) {
297
//                    $locElem = $instanceForm->getBaseFieldset()->get('geo-location');
298
//                    if ($locElem instanceof \Geo\Form\GeoText) {
299
//                        $loc = $locElem->getValue('entity');
300
//                        $locations = $jobEntity->getLocations();
301
//                        if (count($locations)) {
302
//                            $locations->clear();
303
//                        }
304
//                        $locations->add($loc);
305
//                        $jobEntity->setLocation($locElem->getValue());
306
//                    }
307
//                }
308
309
                $title = $jobEntity->getTitle();
310
                $templateTitle = $jobEntity->getTemplateValues()->getTitle();
311
312
                if (empty($templateTitle)) {
313
                    $jobEntity->getTemplateValues()->setTitle($title);
314
                }
315
                $this->repositoryService->store($jobEntity);
316
            }
317
        }
318
319
        // validation
320
        $jobValid = true;
321
        $errorMessage = array();
322
        if (empty($jobEntity->getTitle())) {
323
            $jobValid = false;
324
            $errorMessage[] = $this->translator->translate('No Title');
325
        }
326
        if (!$jobEntity->getLocations()->count()) {
327
            $jobValid = false;
328
            $errorMessage[] = $this->translator->translate('No Location');
329
        }
330
        if (empty($jobEntity->getTermsAccepted())) {
331
            $jobValid = false;
332
            $errorMessage[] = $this->translator->translate('Accept the Terms');
333
        }
334
        $result = $formEvents->trigger('ValidateJob', $this, [ 'form' => $form ]);
335
        foreach ($result as $messages) {
336
            if (!$messages) {
337
                continue;
338
            }
339
            if (!is_array($messages)) {
340
                $messages = [ $messages ];
341
            }
342
343
            $errorMessage = array_merge($errorMessage, $messages);
344
            $jobValid = false;
345
        }
346
347
        $errorMessage = '<br />' . implode('<br />', $errorMessage);
348
        if ($isAjax) {
349
            if ($instanceForm instanceof SummaryForm) {
350
                $instanceForm->setRenderMode(SummaryForm::RENDER_SUMMARY);
351
                $viewHelper = 'summaryForm';
352
            } else {
353
                $viewHelper = 'form';
354
            }
355
            $viewHelperManager  = $this->viewHelper;
356
            $content = $viewHelperManager->get($viewHelper)->__invoke($instanceForm);
357
            $viewModel = new JsonModel(
358
                array(
359
                'content' => $content,
360
                'valid' => $valid,
361
                'jobvalid' => $jobValid,
362
                'errors' => $formErrorMessages,
363
                'errorMessage' => $errorMessage,
364
                'displayMode' => $this->params()->fromQuery('displayMode', 'summary'))
365
            );
366
        } else {
367
            if ($jobEntity->isDraft()) {
368
                $form->getForm('general.nameForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
0 ignored issues
show
Bug introduced by
The method setDisplayMode() 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

368
                $form->getForm('general.nameForm')->/** @scrutinizer ignore-call */ setDisplayMode(SummaryFormInterface::DISPLAY_FORM);

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...
Bug introduced by
The method setDisplayMode() does not exist on Laminas\Form\FormInterface. It seems like you code against a sub-type of Laminas\Form\FormInterface such as Core\Form\SummaryFormInterface or Core\Form\SummaryForm. ( Ignorable by Annotation )

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

368
                $form->getForm('general.nameForm')->/** @scrutinizer ignore-call */ setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
Loading history...
369
                $form->getForm('general.portalForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
370
                $locElem = $form->getForm('general.locationForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM)
371
                                ->getBaseFieldset()->get('geoLocation');
372
                if ($locElem instanceof \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...
373
                    $loc = $jobEntity->getLocations();
374
                    if (count($loc)) {
375
                        $locElem->setValue($loc->first());
376
                    }
377
                }
378
            } else {
379
                $formEvents->trigger('DisableElements', $this, [ 'form' => $form, 'job'=>$jobEntity ]);
380
                // Job is deployed, some changes are now disabled
381
                $form->enableAll();
382
            }
383
384
385
            $completionLink = $this->url()->fromRoute(
386
                'lang/jobs/completion',
387
                [ 'id' => $jobEntity->getId()]
388
            );
389
390
            $viewModel = $this->getViewModel($form);
391
392
            $viewModel->setVariables(
393
                array(
394
                'completionLink' => $completionLink,
395
                'title' => $jobEntity->getTitle(),
396
                'job' => $jobEntity,
397
                'summary' => 'this is what we charge you for your offer...',
398
                'valid' => $valid,
399
                'jobvalid' => $jobValid,
400
                'errorMessage' => $errorMessage,
401
                'isDraft' => $jobEntity->isDraft()
402
                )
403
            );
404
        }
405
        return $viewModel;
406
    }
407
408
    protected function changeStatus(JobInterface $job, $status)
409
    {
410
        if ($job instanceOf JobSnapshot) {
411
            $job = $job->getOriginalEntity();
412
        }
413
414
        $oldStatus = $job->getStatus();
415
416
        if ($status == $oldStatus->getName()) {
0 ignored issues
show
Bug introduced by
The method getName() does not exist on Core\Entity\Status\StatusInterface. It seems like you code against a sub-type of Core\Entity\Status\StatusInterface such as Jobs\Entity\Status. ( Ignorable by Annotation )

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

416
        if ($status == $oldStatus->/** @scrutinizer ignore-call */ getName()) {
Loading history...
417
            return;
418
        }
419
        $user = $this->auth->getUser();
420
        try {
421
            $job->changeStatus($status, sprintf('Status changed from %s to %s by %s', $oldStatus->getName(), $status, $user->getInfo()->getDisplayName()));
0 ignored issues
show
Bug introduced by
The method changeStatus() does not exist on Jobs\Entity\JobInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Jobs\Entity\JobInterface. ( Ignorable by Annotation )

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

421
            $job->/** @scrutinizer ignore-call */ 
422
                  changeStatus($status, sprintf('Status changed from %s to %s by %s', $oldStatus->getName(), $status, $user->getInfo()->getDisplayName()));
Loading history...
Bug introduced by
The method changeStatus() does not exist on Jobs\Entity\JobSnapshotMeta. ( Ignorable by Annotation )

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

421
            $job->/** @scrutinizer ignore-call */ 
422
                  changeStatus($status, sprintf('Status changed from %s to %s by %s', $oldStatus->getName(), $status, $user->getInfo()->getDisplayName()));

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...
422
423
            $events = $this->jobEvents;
424
            $events->trigger(JobEvent::EVENT_STATUS_CHANGED, $this, ['job' => $job, 'status' => $oldStatus]);
425
            $this->notification()->success(/*@translate*/ 'Status successfully changed.');
426
        } catch (\DomainException $e) {
427
            $this->notification()->error(/*@translate*/ 'Change status failed.');
428
        }
429
    }
430
431
    /**
432
     * @return array
433
     */
434
    public function checkApplyIdAction()
435
    {
436
        $validator = $this->validatorManager->get('Jobs/Form/UniqueApplyId');
437
        if (!$validator->isValid($this->params()->fromQuery('applyId'))) {
438
            return array(
439
                'ok' => false,
440
                'messages' => $validator->getMessages(),
441
            );
442
        }
443
        return array('ok' => true);
444
    }
445
446
    /**
447
     * @param  $job \Jobs\Entity\Job
448
     * @return mixed
449
     */
450
    protected function getFormular($job)
451
    {
452
        /* @var $forms \Laminas\Form\FormElementManager */
453
        $forms    = $this->formManager;
454
        /* @var $container \Jobs\Form\Job */
455
456
        $container = $forms->get(
457
            'Jobs/Job',
458
            array(
459
            'mode' => $job->getId() ? 'edit' : 'new'
460
            )
461
        );
462
        $container->setEntity($job);
463
        $container->setParam('job', $job->getId());
0 ignored issues
show
Bug introduced by
The method getId() does not exist on Core\Entity\EntityInterface. It seems like you code against a sub-type of Core\Entity\EntityInterface such as Organizations\Entity\OrganizationInterface or Core\Entity\ImageInterface or Cv\Entity\CvInterface or Applications\Entity\ApplicationInterface or Core\Entity\Tree\NodeInterface or Jobs\Entity\JobInterface or Organizations\Entity\OrganizationNameInterface or Auth\Entity\SocialProfiles\ProfileInterface or Applications\Entity\Subscriber or Settings\Entity\SettingsContainer or Settings\Entity\ModuleSettingsContainer or Core\Entity\AbstractIdentifiableEntity or Cv\Entity\Language or Core\Entity\Tree\AttachedLeafs or Organizations\Entity\OrganizationContact or Cv\Entity\PreferredJob. ( Ignorable by Annotation )

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

463
        $container->setParam('job', $job->/** @scrutinizer ignore-call */ getId());
Loading history...
464
        $container->setParam('snapshot', $job instanceOf JobSnapshot ? $job->getSnapshotId() : '');
465
        $container->setParam('applyId', $job->getApplyId());
0 ignored issues
show
Bug introduced by
The method getApplyId() does not exist on Core\Entity\EntityInterface. It seems like you code against a sub-type of Core\Entity\EntityInterface such as Jobs\Entity\JobInterface or Settings\Entity\SettingsContainer or Settings\Entity\ModuleSettingsContainer or Jobs\Entity\Job. ( Ignorable by Annotation )

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

465
        $container->setParam('applyId', $job->/** @scrutinizer ignore-call */ getApplyId());
Loading history...
466
        return $container;
467
    }
468
469
    /**
470
     * @param $form
471
     * @param array $params
472
     * @return ViewModel
473
     */
474
    protected function getViewModel($form, array $params = array())
475
    {
476
        $variables = array(
477
            'form' => $form,
478
        );
479
        $viewVars  = array_merge($variables, $params);
480
481
        $model = new ViewModel($viewVars);
482
        $model->setTemplate("jobs/manage/form");
483
484
        return $model;
485
    }
486
487
    /**
488
     * Job opening is completed.
489
     *
490
     * @return array
491
     */
492
    public function completionAction()
493
    {
494
495
        $job = $this->initializeJob()->get($this->params(), false, true);
496
497
        if ($job->isDraft()) {
498
499
            $job->setIsDraft(false);
500
501
            $reference = $job->getReference();
502
503
            if (empty($reference)) {
504
                /* @var $repository \Jobs\Repository\Job */
505
                $repository = $this->repositoryService->get('Jobs/Job');
506
                $job->setReference($repository->getUniqueReference());
507
            }
508
            $job->changeStatus(Status::CREATED, "job was created");
509
            $job->setAtsEnabled(true);
510
511
            // sets ATS-Mode on intern
512
            $job->getAtsMode();
513
514
            /*
515
            * make the job opening persist and fire the EVENT_JOB_CREATED
516
            */
517
            $this->repositoryService->store($job);
518
519
            $jobEvents = $this->jobEvents;
520
            $jobEvents->trigger(JobEvent::EVENT_JOB_CREATED, $this, array('job' => $job));
521
        } else if ($job->isActive()) {
522
            $eventParams = [
523
                'job' => $job,
524
                'statusWas' => $job->getStatus()->getName(),
0 ignored issues
show
Deprecated Code introduced by
The function Jobs\Entity\Status::getName() has been deprecated: since 0,29, use __toString() ( Ignorable by Annotation )

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

524
                'statusWas' => /** @scrutinizer ignore-deprecated */ $job->getStatus()->getName(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
525
            ];
526
            $job->getOriginalEntity()->changeStatus(Status::WAITING_FOR_APPROVAL, 'job was edited.');
0 ignored issues
show
introduced by
The method getOriginalEntity() does not exist on Jobs\Entity\Job. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

526
            $job->/** @scrutinizer ignore-call */ 
527
                  getOriginalEntity()->changeStatus(Status::WAITING_FOR_APPROVAL, 'job was edited.');
Loading history...
527
            $this->jobEvents->trigger(JobEvent::EVENT_STATUS_CHANGED, $this, $eventParams);
528
        }
529
530
        /* @var \Auth\Controller\Plugin\UserSwitcher $switcher */
531
        $switcher = $this->plugin('Auth/User/Switcher');
532
        if ($switcher->isSwitchedUser()) {
533
            $return = $switcher->getSessionParam('return');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $return is correct as $switcher->getSessionParam('return') targeting Auth\Controller\Plugin\U...cher::getSessionParam() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
534
            $switcher->clear();
535
536
            if ($return) {
0 ignored issues
show
introduced by
$return is of type null, thus it always evaluated to false.
Loading history...
537
                return $this->redirect()->toUrl($return);
538
            }
539
        }
540
541
        return array('job' => $job);
542
    }
543
544
    /**
545
     * all actions around approve or decline jobs-offers
546
     *
547
     * @return array with the viewVariables
548
     */
549
    public function approvalAction()
550
    {
551
        $user           = $this->auth->getUser();
552
553
        $params         = $this->params('state');
554
555
        $jobEntity = $this->initializeJob()->get($this->params(), false, true);
556
        $jobEvent       = $this->jobEvent;
557
        $jobEvent->setJobEntity($jobEntity);
0 ignored issues
show
Bug introduced by
The method setJobEntity() does not exist on Laminas\EventManager\EventInterface. It seems like you code against a sub-type of Laminas\EventManager\EventInterface such as Jobs\Listener\Events\JobEvent. ( Ignorable by Annotation )

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

557
        $jobEvent->/** @scrutinizer ignore-call */ 
558
                   setJobEntity($jobEntity);
Loading history...
558
        $jobEvent->addPortal('XingVendorApi');
0 ignored issues
show
Bug introduced by
The method addPortal() does not exist on Laminas\EventManager\EventInterface. It seems like you code against a sub-type of Laminas\EventManager\EventInterface such as Jobs\Listener\Events\JobEvent. ( Ignorable by Annotation )

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

558
        $jobEvent->/** @scrutinizer ignore-call */ 
559
                   addPortal('XingVendorApi');
Loading history...
559
        $jobEvent->setTarget($this);
560
        $jobEvents      = $this->jobEvents;
561
        // array with differences between the last snapshot and the actual entity
562
        // is remains Null if there is no snapshot
563
        // it will be an empty array if the snapshot and the actual entity do not differ
564
        $diff           = null;
565
566
567
        if ($params == 'declined') {
568
            if ($jobEntity instanceOf JobSnapshot)  {
569
                $jobEntity->getOriginalEntity()->changeStatus(
570
                    Status::ACTIVE,
571
                    sprintf(
572
                        /*@translate*/ 'Changes were rejected by %s',
573
                        $user->getInfo()->getDisplayName()
574
                    )
575
                );
576
                $jobEntity->getSnapshotMeta()->setStatus(JobSnapshotStatus::REJECTED)->setIsDraft(false);
577
            } else {
578
                $jobEntity->changeStatus(
579
                    Status::REJECTED,
580
                    sprintf(
581
                        /*@translate*/ "Job opening was rejected by %s",
582
                        $user->getInfo()->getDisplayName()
583
                    )
584
                );
585
                $jobEntity->setIsDraft(true);
586
            }
587
588
            $this->repositoryService->store($jobEntity);
589
            $jobEvent->setName(JobEvent::EVENT_JOB_REJECTED);
590
591
            $jobEvents->trigger($jobEvent);
0 ignored issues
show
Bug introduced by
$jobEvent of type Laminas\EventManager\EventInterface is incompatible with the type string expected by parameter $eventName of Laminas\EventManager\Eve...gerInterface::trigger(). ( Ignorable by Annotation )

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

591
            $jobEvents->trigger(/** @scrutinizer ignore-type */ $jobEvent);
Loading history...
592
            $this->notification()->success(/*@translate */'Job has been rejected');
593
        }
594
595
        if ($params == 'approved') {
596
            if ($jobEntity instanceOf JobSnapshot) {
597
                $jobEntity->getSnapshotMeta()->setStatus(JobSnapshotStatus::ACCEPTED);
598
                $jobEntity = $this->repositoryService->get('Jobs/JobSnapshot')->merge($jobEntity);
0 ignored issues
show
Bug introduced by
The method merge() does not exist on Doctrine\Persistence\ObjectRepository. It seems like you code against a sub-type of Doctrine\Persistence\ObjectRepository such as Core\Repository\SnapshotRepository. ( Ignorable by Annotation )

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

598
                $jobEntity = $this->repositoryService->get('Jobs/JobSnapshot')->/** @scrutinizer ignore-call */ merge($jobEntity);
Loading history...
599
                $jobEntity->setDateModified();
600
            } else {
601
                $jobEntity->setDatePublishStart();
602
            }
603
            $jobEntity->changeStatus(Status::ACTIVE, sprintf(/*@translate*/ "Job opening was activated by %s", $user->getInfo()->getDisplayName()));
604
            $this->repositoryService->store($jobEntity);
605
            $jobEvent->setName(JobEvent::EVENT_JOB_ACCEPTED);
606
            $jobEvents->trigger($jobEvent);
607
            //$this->entitySnapshot($jobEntity);
608
            $this->notification()->success(/* @translate */ 'Job has been approved');
609
            return $this->redirect()->toRoute('lang/admin/jobs', array('lang' => $this->params('lang')));
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->redirect()...$this->params('lang'))) returns the type Laminas\Http\Response which is incompatible with the documented return type array.
Loading history...
610
        }
611
612
        $query = /*$jobEntity instanceOf JobSnapshot ? ['snapshot' => $jobEntity->getSnapshotId()] : */['id' => $jobEntity->getId()];
613
        $viewLink = $this->url()->fromRoute(
614
            'lang/jobs/view',
615
            array(),
616
            array('query' => $query
617
                      )
618
        );
619
620
        $approvalLink = $this->url()->fromRoute(
621
            'lang/jobs/approval',
622
            array('state' => 'approved'),
623
            array('query' => $query)
624
        );
625
626
        $declineLink = $this->url()->fromRoute(
627
            'lang/jobs/approval',
628
            array('state' => 'declined'),
629
            array('query' => $query)
630
        );
631
632
        return array('job' => $jobEntity,
633
                     'diffSnapshot' => $diff,
634
                     'viewLink' => $viewLink,
635
                     'approvalLink' => $approvalLink,
636
                     'declineLink' => $declineLink);
637
    }
638
639
    /**
640
     * Deactivate a job posting
641
     *
642
     * @return null|ViewModel
643
     */
644
    public function deactivateAction()
645
    {
646
        $user           = $this->auth->getUser();
647
648
        $jobEntity = $this->initializeJob()->get($this->params());
649
650
        try {
651
            $jobEntity->changeStatus(Status::INACTIVE, sprintf(/*@translate*/ "Job was deactivated by %s", $user->getInfo()->getDisplayName()));
652
            $this->notification()->success(/*@translate*/ 'Job has been deactivated');
653
        } catch (\Exception $e) {
654
            $this->notification()->danger(/*@translate*/ 'Job could not be deactivated');
655
        }
656
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
657
        return $this->save(array('page' => 2));
0 ignored issues
show
Unused Code introduced by
return $this->save(array('page' => 2)) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
658
    }
659
660
    public function deleteAction()
661
    {
662
        $job = $this->initializeJob()->get($this->params());
663
        $this->acl($job, 'edit');
0 ignored issues
show
Unused Code introduced by
The call to Jobs\Controller\ManageController::acl() has too many arguments starting with $job. ( Ignorable by Annotation )

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

663
        $this->/** @scrutinizer ignore-call */ 
664
               acl($job, 'edit');

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. Please note the @ignore annotation hint above.

Loading history...
664
665
        $this->repositoryService->remove($job, true);
666
667
        $this->notification()->success(/*@translate*/ 'Job has been deleted.');
668
        return $this->redirect()->toRoute('lang/jobs');
669
    }
670
671
    /**
672
     * Assign a template to a job posting
673
     *
674
     * @return JsonModel
675
     */
676
    public function templateAction()
677
    {
678
        try {
679
            $jobEntity = $this->initializeJob()->get($this->params());
680
            $jobEntity->setTemplate($this->params('template', 'default'));
0 ignored issues
show
Bug introduced by
It seems like $this->params('template', 'default') can also be of type Laminas\Mvc\Controller\Plugin\Params; however, parameter $template of Jobs\Entity\Job::setTemplate() 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

680
            $jobEntity->setTemplate(/** @scrutinizer ignore-type */ $this->params('template', 'default'));
Loading history...
681
            $this->repositoryService->store($jobEntity);
682
            $this->notification()->success(/* @translate*/ 'Template changed');
683
        } catch (\Exception $e) {
684
            $this->notification()->danger(/* @translate */ 'Template not changed');
685
        }
686
687
        return new JsonModel(array());
688
    }
689
690
    /**
691
     * @param $script
692
     * @param array $parameter
693
     * @return ViewModel
694
     */
695
    protected function getErrorViewModel($script, $parameter = array())
696
    {
697
        /** @var Response $response */
698
        $response = $this->getResponse();
699
        $response->setStatusCode(Response::STATUS_CODE_500);
700
701
        $model = new ViewModel($parameter);
702
        $model->setTemplate("jobs/error/$script");
703
704
        return $model;
705
    }
706
707
    public function historyAction()
708
    {
709
        $jobEntity = $this->initializeJob()->get($this->params());
710
        $title          = $jobEntity->getTitle();
711
        $historyEntity  = $jobEntity->getHistory();
712
713
        $model = new ViewModel(array('title' => $title, 'history' => $historyEntity));
714
        $model->setTerminal(true);
715
        return $model;
716
    }
717
}
718