Completed
Push — develop ( 8e0188...beb977 )
by
unknown
07:35
created

ManageController::attachDefaultListeners()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 12
loc 12
rs 9.4285
cc 1
eloc 9
nc 1
nop 0
1
<?php
2
3
/**
4
 * YAWIK
5
 *
6
 * @filesource
7
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
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\Status;
17
use Core\Repository\RepositoryService;
18
use Zend\Mvc\Controller\AbstractActionController;
19
use Zend\View\Model\ViewModel;
20
use Zend\View\Model\JsonModel;
21
use Core\Form\SummaryForm;
22
use Zend\Mvc\MvcEvent;
23
use Jobs\Listener\Events\JobEvent;
24
use Core\Form\SummaryFormInterface;
25
use Zend\Stdlib\ArrayUtils;
26
use Auth\AuthenticationService;
27
use Zend\Mvc\I18n\Translator;
28
use Zend\Http\PhpEnvironment\Response;
29
use Core\Entity\Exception\NotFoundException;
30
31
/**
32
 * This Controller handles management actions for jobs.
33
 *
34
 * @method \Acl\Controller\Plugin\Acl acl()
35
 * @method \Jobs\Controller\Plugin\InitializeJob initializeJob()
36
 * @method \Core\Controller\Plugin\Notification notification()
37
 * @method \Core\Controller\Plugin\EntitySnapshot entitySnapshot()
38
 *
39
 * @author Mathias Gelhausen <[email protected]>
40
 * @author Mathias Weitz <[email protected]>
41
 * @author Carsten Bleek <[email protected]>
42
 * @author Rafal Ksiazek
43
 * @author Miroslav Fedeleš <[email protected]>
44
 */
45
class ManageController extends AbstractActionController
46
{
47
    /**
48
     * @var AuthenticationService
49
     */
50
    protected $auth;
51
52
    /**
53
     * @var RepositoryService
54
     */
55
    protected $repositoryService;
56
57
    /**
58
     * @var Translator
59
     */
60
    protected $translator;
61
62
    /**
63
     * @param AuthenticationService $auth
64
     * @param RepositoryService     $repositoryService
65
     * @param                       $translator
66
     */
67
    public function __construct(AuthenticationService $auth, RepositoryService $repositoryService, Translator $translator)
68
    {
69
        $this->auth = $auth;
70
        $this->repositoryService = $repositoryService;
71
        $this->translator = $translator;
72
    }
73
74
    /**
75
     * @return $this|void
76
     */
77 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...
78
    {
79
        parent::attachDefaultListeners();
80
        $events = $this->getEventManager();
81
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
82
        $serviceLocator = $this->serviceLocator;
83
        $defaultServices = $serviceLocator->get('DefaultListeners');
84
        $events = $this->getEventManager();
85
        $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...
86
87
        return $this;
88
    }
89
90
    /**
91
     * Dispatch listener callback.
92
     *
93
     * Attaches the MailSender aggregate listener to the job event manager.
94
     *
95
     * @param MvcEvent $e
96
     * @since 0.19
97
     */
98
    public function preDispatch(MvcEvent $e)
99
    {
100
        if ('calculate' == $this->params()->fromQuery('do')) {
101
            return;
102
        }
103
        $routeMatch = $e->getRouteMatch();
104
        $action = $routeMatch->getParam('action');
105
106
        if (in_array($action, array('edit', 'approval', 'completion'))) {
107
            $services = $this->serviceLocator;
108
            $jobEvents = $services->get('Jobs/Events');
109
            $mailSender = $services->get('Jobs/Listener/MailSender');
110
111
            $mailSender->attach($jobEvents);
112
        }
113
    }
114
115
    /**
116
     *
117
     *
118
     * @return null|ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be ViewModel|array<string,string|NotFoundException>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
119
     */
120
    public function editAction()
121
    {
122
        if ('calculate' == $this->params()->fromQuery('do')) {
123
            $calc = $this->serviceLocator->get('filtermanager')->get('Jobs/ChannelPrices');
124
            $sum = $calc->filter($this->params()->fromPost('channels'));
125
126
            return new JsonModel(['sum' => $sum]);
127
        }
128
129
        return $this->save();
130
    }
131
132
    /**
133
     * @return null|ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be ViewModel|array<string,string|NotFoundException>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
134
     */
135
    public function saveAction()
136
    {
137
        return $this->save();
138
    }
139
140
    public function channelListAction()
141
    {
142
        $serviceLocator = $this->serviceLocator;
143
        $options = $serviceLocator->get('Core/Options');
144
        $channels = $serviceLocator->get('Jobs/Options/Provider');
145
146
147
148
        $jobEntity = $this->initializeJob()->get($this->params(), true);
149
150
        $model = new ViewModel([
151
                                   'portals' => $jobEntity->getPortals(),
152
                                   'channels' => $channels,
153
                                   'defaultCurrencyCode' => $options->defaultCurrencyCode,
154
                                   'defaultTaxRate' =>  $options->defaultTaxRate,
155
                                   'jobId' => $jobEntity->getId()
156
                               ]);
157
        $model->setTemplate('jobs/partials/channel-list')->setTerminal(true);
158
        return $model;
159
    }
160
161
    /**
162
     * save a Job-Post either by a regular request or by an async post (AJAX)
163
     * a mandatory parameter is the ID of the Job
164
     * in case of a regular Request you can
165
     *
166
     * parameter are arbitrary elements for defaults or programming flow
167
     *
168
     * @param array $parameter
0 ignored issues
show
Bug introduced by
There is no parameter named $parameter. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
169
     * @return null|ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be ViewModel|array<string,string|NotFoundException>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
170
     * @throws \RuntimeException
171
     */
172
    protected function save()
173
    {
174
        $serviceLocator     = $this->serviceLocator;
175
        $formEvents         = $serviceLocator->get('Jobs/JobContainer/Events');
176
177
        $user               = $this->auth->getUser();
178
        if (empty($user->getInfo()->getEmail())) {
179
            return $this->getErrorViewModel('no-parent', array('cause' => 'noEmail'));
180
        }
181
        $userOrg            = $user->getOrganization();
182
        if (!$userOrg->hasAssociation() || $userOrg->getOrganization()->isDraft()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Organizations\Entity\OrganizationInterface as the method isDraft() does only exist in the following implementations of said interface: Organizations\Entity\Organization.

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...
183
            return $this->getErrorViewModel('no-parent', array('cause' => 'noCompany'));
184
        }
185
        
186
        try {
187
            $jobEntity = $this->initializeJob()->get($this->params(), true, true);
188
        } catch (NotFoundException $e) {
189
            $this->getResponse()->setStatusCode(Response::STATUS_CODE_404);
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...
190
            return [
191
                'message' => sprintf($this->translator->translate('Job with id "%s" not found'), $e->getId()),
192
                'exception' => $e
193
            ];
194
        }
195
196
197
        /** @var \Zend\Http\Request $request */
198
        $request            = $this->getRequest();
199
        $isAjax             = $request->isXmlHttpRequest();
200
201
        $params             = $this->params();
202
        $formIdentifier     = $params->fromQuery('form');
203
204
        if ('1' == $params->fromQuery('admin')) {
205
            /* @var \Auth\Controller\Plugin\UserSwitcher $switcher */
206
            $switcher = $this->plugin('Auth/User/Switcher');
207
            $switcher($jobEntity->getUser(), ['return' => urldecode($params->fromQuery('return'))]);
208
        }
209
210
211
        $viewModel          = null;
0 ignored issues
show
Unused Code introduced by
$viewModel is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
212
        $this->acl($jobEntity, 'edit');
0 ignored issues
show
Unused Code introduced by
The call to ManageController::acl() has too many arguments starting with $jobEntity.

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
213
        if ($status = $params->fromQuery('status')) {
214
            $this->changeStatus($jobEntity, $status);
215
        }
216
217
        $form               = $this->getFormular($jobEntity);
218
219
        $valid              = true;
220
        $instanceForm       = null;
221
        $formErrorMessages = array();
222
223
        if (isset($formIdentifier) &&  $request->isPost()) {
224
            // at this point the form get instantiated and immediately accumulated
225
            $instanceForm = $form->getForm($formIdentifier);
226
            if (!isset($instanceForm)) {
227
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
228
            }
229
            // the id may be part of the postData, but it never should be altered
230
            $postData = $request->getPost();
231
            if (isset($postData['id'])) {
232
                unset($postData['id']);
233
            }
234
            unset($postData['applyId']);
235
            $instanceForm->setData($postData);
236
            $valid = $instanceForm->isValid();
237
            $formErrorMessages = ArrayUtils::merge($formErrorMessages, $instanceForm->getMessages());
238
            if ($valid) {
239
                /*
240
                 * @todo This is a workaround for GeoJSON data insertion
241
                 * until we figured out, what we really want it to be.
242
                 */
243
//                if ('general.locationForm' == $formIdentifier) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
244
//                    $locElem = $instanceForm->getBaseFieldset()->get('geo-location');
245
//                    if ($locElem instanceof \Geo\Form\GeoText) {
246
//                        $loc = $locElem->getValue('entity');
247
//                        $locations = $jobEntity->getLocations();
248
//                        if (count($locations)) {
249
//                            $locations->clear();
250
//                        }
251
//                        $locations->add($loc);
252
//                        $jobEntity->setLocation($locElem->getValue());
253
//                    }
254
//                }
255
256
                $title = $jobEntity->getTitle();
257
                $templateTitle = $jobEntity->getTemplateValues()->getTitle();
258
259
                if (empty($templateTitle)) {
260
                    $jobEntity->getTemplateValues()->setTitle($title);
261
                }
262
                $this->repositoryService->store($jobEntity);
263
            }
264
        }
265
266
        // validation
267
        $jobValid = true;
268
        $errorMessage = array();
269
        if (empty($jobEntity->getTitle())) {
270
            $jobValid = false;
271
            $errorMessage[] = $this->translator->translate('No Title');
272
        }
273
        if (!$jobEntity->getLocations()->count()) {
274
            $jobValid = false;
275
            $errorMessage[] = $this->translator->translate('No Location');
276
        }
277
        if (empty($jobEntity->getTermsAccepted())) {
278
            $jobValid = false;
279
            $errorMessage[] = $this->translator->translate('Accept the Terms');
280
        }
281
        $result = $formEvents->trigger('ValidateJob', $this, [ 'form' => $form ]);
282
        foreach ($result as $messages) {
283
            if (!$messages) {
284
                continue;
285
            }
286
            if (!is_array($messages)) {
287
                $messages = [ $messages ];
288
            }
289
290
            $errorMessage = array_merge($errorMessage, $messages);
291
            $jobValid = false;
292
        }
293
294
        $errorMessage = '<br />' . implode('<br />', $errorMessage);
295
        if ($isAjax) {
296
            if ($instanceForm instanceof SummaryForm) {
297
                $instanceForm->setRenderMode(SummaryForm::RENDER_SUMMARY);
298
                $viewHelper = 'summaryform';
299
            } else {
300
                $viewHelper = 'form';
301
            }
302
            $viewHelperManager  = $serviceLocator->get('ViewHelperManager');
303
            $content = $viewHelperManager->get($viewHelper)->__invoke($instanceForm);
304
            $viewModel = new JsonModel(
305
                array(
306
                'content' => $content,
307
                'valid' => $valid,
308
                'jobvalid' => $jobValid,
309
                'errors' => $formErrorMessages,
310
                'errorMessage' => $errorMessage)
311
            );
312
        } else {
313
            if ($jobEntity->isDraft()) {
314
                $form->getForm('general.nameForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
315
                $form->getForm('general.portalForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
316
                $locElem = $form->getForm('general.locationForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM)
317
                                ->getBaseFieldset()->get('geoLocation');
318
                if ($locElem instanceof \Geo\Form\GeoText) {
319
                    $loc = $jobEntity->getLocations();
320
                    if (count($loc)) {
321
                        $locElem->setValue($loc->first());
322
                    }
323
                }
324
            } else {
325
                $formEvents->trigger('DisableElements', $this, [ 'form' => $form, 'job'=>$jobEntity ]);
326
                // Job is deployed, some changes are now disabled
327
                $form->enableAll();
328
            }
329
330
331
            $completionLink = $this->url()->fromRoute(
332
                'lang/jobs/completion',
333
                [ 'id' => $jobEntity->getId()]
334
            );
335
336
            $viewModel = $this->getViewModel($form);
337
338
            $viewModel->setVariables(
339
                array(
340
                'completionLink' => $completionLink,
341
                'title' => $jobEntity->getTitle(),
342
                'job' => $jobEntity,
343
                'summary' => 'this is what we charge you for your offer...',
344
                'valid' => $valid,
345
                'jobvalid' => $jobValid,
346
                'errorMessage' => $errorMessage,
347
                'isDraft' => $jobEntity->isDraft()
348
                )
349
            );
350
        }
351
        return $viewModel;
352
    }
353
354
    protected function changeStatus(JobInterface $job, $status)
355
    {
356
        if ($job instanceOf JobSnapshot) {
357
            $job = $job->getSnapshotMeta()->getEntity();
358
        }
359
360
        $oldStatus = $job->getStatus();
361
362
        if ($status == $oldStatus->getName()) {
363
            return;
364
        }
365
        $user = $this->auth->getUser();
366
        try {
367
            $job->changeStatus($status, sprintf('Status changed from %s to %s by %s', $oldStatus->getName(), $status, $user->getInfo()->getDisplayName()));
368
369
            $events = $this->serviceLocator->get('Jobs/Events');
370
            $events->trigger(JobEvent::EVENT_STATUS_CHANGED, $this, ['job' => $job, 'status' => $oldStatus]);
371
            $this->notification()->success(/*@translate*/ 'Status successfully changed.');
372
        } catch (\DomainException $e) {
373
            $this->notification()->error(/*@translate*/ 'Change status failed.');
374
        }
375
    }
376
377
    /**
378
     * @return array
379
     */
380
    public function checkApplyIdAction()
381
    {
382
        $services = $this->serviceLocator;
383
        $validator = $services->get('validatormanager')->get('Jobs/Form/UniqueApplyId');
384
        if (!$validator->isValid($this->params()->fromQuery('applyId'))) {
385
            return array(
386
                'ok' => false,
387
                'messages' => $validator->getMessages(),
388
            );
389
        }
390
        return array('ok' => true);
391
    }
392
393
    /**
394
     * @param  $job \Jobs\Entity\Job
395
     * @return mixed
396
     */
397
    protected function getFormular($job)
398
    {
399
        $services = $this->serviceLocator;
400
        /* @var $forms \Zend\Form\FormElementManager */
401
        $forms    = $services->get('FormElementManager');
402
        /* @var $container \Jobs\Form\Job */
403
404
        $container = $forms->get(
405
            'Jobs/Job',
406
            array(
407
            'mode' => $job->getId() ? 'edit' : 'new'
408
            )
409
        );
410
        $container->setEntity($job);
411
        $container->setParam('job', $job->getId());
412
        $container->setParam('snapshot', $job instanceOf JobSnapshot ? $job->getSnapshotId() : '');
413
        $container->setParam('applyId', $job->getApplyId());
414
        return $container;
415
    }
416
417
    /**
418
     * @param $form
419
     * @param array $params
420
     * @return ViewModel
421
     */
422
    protected function getViewModel($form, array $params = array())
423
    {
424
        $variables = array(
425
            'form' => $form,
426
        );
427
        $viewVars  = array_merge($variables, $params);
428
        
429
        $model = new ViewModel($viewVars);
430
        $model->setTemplate("jobs/manage/form");
431
        
432
        return $model;
433
    }
434
435
    /**
436
     * Job opening is completed.
437
     *
438
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be \Zend\Http\Response|array<string,object>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
439
     */
440
    public function completionAction()
441
    {
442
        $serviceLocator = $this->serviceLocator;
443
444
        $job = $this->initializeJob()->get($this->params(), false, true);
445
446
        if ($job->isDraft()) {
447
448
            $job->setIsDraft(false);
449
450
            $reference = $job->getReference();
451
452
            if (empty($reference)) {
453
                /* @var $repository \Jobs\Repository\Job */
454
                $repository = $this->repositoryService->get('Jobs/Job');
455
                $job->setReference($repository->getUniqueReference());
456
            }
457
            $job->changeStatus(Status::CREATED, "job was created");
458
            $job->setAtsEnabled(true);
459
460
            // sets ATS-Mode on intern
461
            $job->getAtsMode();
462
463
            /*
464
            * make the job opening persist and fire the EVENT_JOB_CREATED
465
            */
466
            $this->repositoryService->store($job);
467
468
            $jobEvents = $serviceLocator->get('Jobs/Events');
469
            $jobEvents->trigger(JobEvent::EVENT_JOB_CREATED, $this, array('job' => $job));
470
        } else if ($job->isActive()) {
471
            $job->getSnapshotMeta()->getEntity()->changeStatus(Status::WAITING_FOR_APPROVAL, 'job was edited.');
472
        }
473
474
        /* @var \Auth\Controller\Plugin\UserSwitcher $switcher */
475
        $switcher = $this->plugin('Auth/User/Switcher');
476
        if ($switcher->isSwitchedUser()) {
477
            $return = $switcher->getSessionParam('return');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $return is correct as $switcher->getSessionParam('return') (which targets 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...
478
            $switcher->clear();
479
480
            if ($return) {
481
                return $this->redirect()->toUrl($return);
482
            }
483
        }
484
485
        return array('job' => $job);
486
    }
487
488
    /**
489
     * all actions around approve or decline jobs-offers
490
     *
491
     * @return array with the viewVariables
0 ignored issues
show
Documentation introduced by
Should the return type not be \Zend\Http\Response|arra...ing,object|null|string>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
492
     */
493
    public function approvalAction()
494
    {
495
        $serviceLocator = $this->serviceLocator;
496
        $user           = $this->auth->getUser();
497
498
        $params         = $this->params('state');
499
500
        $jobEntity = $this->initializeJob()->get($this->params(), false, true);
501
        $jobEvent       = $serviceLocator->get('Jobs/Event');
502
        $jobEvent->setJobEntity($jobEntity);
503
        $jobEvent->addPortal('XingVendorApi');
504
        $jobEvents      = $serviceLocator->get('Jobs/Events');
505
        // array with differences between the last snapshot and the actual entity
506
        // is remains Null if there is no snapshot
507
        // it will be an empty array if the snapshot and the actual entity do not differ
508
        $diff           = null;
509
510
511
        if ($params == 'declined') {
512
            $jobEntity->changeStatus(Status::REJECTED, sprintf(/*@translate*/ "Job opening was rejected by %s", $user->getInfo()->getDisplayName()));
513
            $jobEntity->setIsDraft(true);
514
            $this->repositoryService->store($jobEntity);
515
            $jobEvents->trigger(JobEvent::EVENT_JOB_REJECTED, $jobEvent);
516
            $this->notification()->success(/*@translate */'Job has been rejected');
517
        }
518
519
        if ($params == 'approved') {
520
            if ($jobEntity instanceOf JobSnapshot) {
521
                $jobEntity = $this->repositoryService->get('Jobs/JobSnapshot')->merge($jobEntity);
522
            } else {
523
                $jobEntity->setDatePublishStart();
524
            }
525
            $jobEntity->changeStatus(Status::ACTIVE, sprintf(/*@translate*/ "Job opening was activated by %s", $user->getInfo()->getDisplayName()));
526
            $this->repositoryService->store($jobEntity);
527
            $jobEvents->trigger(JobEvent::EVENT_JOB_ACCEPTED, $jobEvent);
528
            //$this->entitySnapshot($jobEntity);
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
529
            $this->notification()->success(/* @translate */ 'Job has been approved');
530
            return $this->redirect()->toRoute('lang/admin/jobs', array('lang' => $this->params('lang')));
531
        }
532
533
        $query = $jobEntity instanceOf JobSnapshot ? ['snapshot' => $jobEntity->getSnapshotId()] : ['id' => $jobEntity->getId()];
534
        $viewLink = $this->url()->fromRoute(
535
            'lang/jobs/view',
536
            array(),
537
            array('query' => $query
538
                      )
539
        );
540
541
        $approvalLink = $this->url()->fromRoute(
542
            'lang/jobs/approval',
543
            array('state' => 'approved'),
544
            array('query' => $query)
545
        );
546
547
        $declineLink = $this->url()->fromRoute(
548
            'lang/jobs/approval',
549
            array('state' => 'declined'),
550
            array('query' => $query)
551
        );
552
553
        return array('job' => $jobEntity,
554
                     'diffSnapshot' => $diff,
555
                     'viewLink' => $viewLink,
556
                     'approvalLink' => $approvalLink,
557
                     'declineLink' => $declineLink);
558
    }
559
560
    /**
561
     * Deactivate a job posting
562
     *
563
     * @return null|ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be ViewModel|array<string,string|NotFoundException>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
564
     */
565
    public function deactivateAction()
566
    {
567
        $user           = $this->auth->getUser();
568
569
        $jobEntity = $this->initializeJob()->get($this->params());
570
571
        try {
572
            $jobEntity->changeStatus(Status::INACTIVE, sprintf(/*@translate*/ "Job was deactivated by %s", $user->getInfo()->getDisplayName()));
573
            $this->notification()->success(/*@translate*/ 'Job has been deactivated');
574
        } catch (\Exception $e) {
575
            $this->notification()->danger(/*@translate*/ 'Job could not be deactivated');
576
        }
577
        return $this->save(array('page' => 2));
0 ignored issues
show
Unused Code introduced by
The call to ManageController::save() has too many arguments starting with array('page' => 2).

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
578
    }
579
580
    public function deleteAction()
581
    {
582
        $job = $this->initializeJob()->get($this->params());
583
        $this->acl($job, 'edit');
0 ignored issues
show
Unused Code introduced by
The call to ManageController::acl() has too many arguments starting with $job.

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
584
585
        $this->repositoryService->remove($job);
586
587
        $this->notification()->success(/*@translate*/ 'Job has been deleted.');
588
        return $this->redirect()->toRoute('lang/jobs');
589
590
    }
591
    /**
592
     * Assign a template to a job posting
593
     *
594
     * @return JsonModel
595
     */
596
    public function templateAction()
597
    {
598
        try {
599
            $jobEntity = $this->initializeJob()->get($this->params());
600
            $jobEntity->setTemplate($this->params('template', 'default'));
601
            $this->repositoryService->store($jobEntity);
602
            $this->notification()->success(/* @translate*/ 'Template changed');
603
        } catch (\Exception $e) {
604
            $this->notification()->danger(/* @translate */ 'Template not changed');
605
        }
606
607
        return new JsonModel(array());
608
    }
609
610
    /**
611
     * @param $script
612
     * @param array $parameter
613
     * @return ViewModel
614
     */
615 View Code Duplication
    protected function getErrorViewModel($script, $parameter = array())
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...
616
    {
617
        /** @var Response $response */
618
        $response = $this->getResponse();
619
        $response->setStatusCode(Response::STATUS_CODE_500);
620
621
        $model = new ViewModel($parameter);
622
        $model->setTemplate("jobs/error/$script");
623
624
        return $model;
625
    }
626
627
    public function historyAction()
628
    {
629
        $jobEntity = $this->initializeJob()->get($this->params());
630
        $title          = $jobEntity->getTitle();
631
        $historyEntity  = $jobEntity->getHistory();
632
633
        $model = new ViewModel(array('title' => $title, 'history' => $historyEntity));
634
        $model->setTerminal(true);
635
        return $model;
636
    }
637
}
638