Completed
Push — develop ( ed00c0...6fcae6 )
by
unknown
07:15
created

ManageController::completionAction()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 36
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 4
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
    public function attachDefaultListeners()
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->info->email)) {
0 ignored issues
show
Documentation introduced by
The property $info is declared protected in Auth\Entity\User. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Bug introduced by
Accessing email on the interface Auth\Entity\InfoInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

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

Available Fixes

  1. Adding an additional type check:

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

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
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
        /** @var \Zend\Http\Request $request */
197
        $request            = $this->getRequest();
198
        $isAjax             = $request->isXmlHttpRequest();
199
200
        $params             = $this->params();
201
        $formIdentifier     = $params->fromQuery('form');
202
203
204
        $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...
205
        $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...
206
        if ($status = $params->fromQuery('status')) {
207
            $this->changeStatus($jobEntity, $status);
208
        }
209
210
        $form               = $this->getFormular($jobEntity);
211
212
        $valid              = true;
213
        $instanceForm       = null;
214
        $formErrorMessages = array();
215
216
        if (isset($formIdentifier) &&  $request->isPost()) {
217
            // at this point the form get instantiated and immediately accumulated
218
            $instanceForm = $form->getForm($formIdentifier);
219
            if (!isset($instanceForm)) {
220
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
221
            }
222
            // the id may be part of the postData, but it never should be altered
223
            $postData = $request->getPost();
224
            if (isset($postData['id'])) {
225
                unset($postData['id']);
226
            }
227
            unset($postData['applyId']);
228
            $instanceForm->setData($postData);
229
            $valid = $instanceForm->isValid();
230
            $formErrorMessages = ArrayUtils::merge($formErrorMessages, $instanceForm->getMessages());
231
            if ($valid) {
232
                /*
233
                 * @todo This is a workaround for GeoJSON data insertion
234
                 * until we figured out, what we really want it to be.
235
                 */
236
//                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...
237
//                    $locElem = $instanceForm->getBaseFieldset()->get('geo-location');
238
//                    if ($locElem instanceof \Geo\Form\GeoText) {
239
//                        $loc = $locElem->getValue('entity');
240
//                        $locations = $jobEntity->getLocations();
241
//                        if (count($locations)) {
242
//                            $locations->clear();
243
//                        }
244
//                        $locations->add($loc);
245
//                        $jobEntity->setLocation($locElem->getValue());
246
//                    }
247
//                }
248
249
                $title = $jobEntity->getTitle();
250
                $templateTitle = $jobEntity->getTemplateValues()->getTitle();
251
252
                if (empty($templateTitle)) {
253
                    $jobEntity->getTemplateValues()->setTitle($title);
254
                }
255
                $this->repositoryService->store($jobEntity);
256
            }
257
        }
258
259
        // validation
260
        $jobValid = true;
261
        $errorMessage = array();
262
        if (empty($jobEntity->getTitle())) {
263
            $jobValid = false;
264
            $errorMessage[] = $this->translator->translate('No Title');
265
        }
266
        if (!$jobEntity->getLocations()->count()) {
267
            $jobValid = false;
268
            $errorMessage[] = $this->translator->translate('No Location');
269
        }
270
        if (empty($jobEntity->getTermsAccepted())) {
271
            $jobValid = false;
272
            $errorMessage[] = $this->translator->translate('Accept the Terms');
273
        }
274
        $result = $formEvents->trigger('ValidateJob', $this, [ 'form' => $form ]);
275
        foreach ($result as $messages) {
276
            if (!$messages) {
277
                continue;
278
            }
279
            if (!is_array($messages)) {
280
                $messages = [ $messages ];
281
            }
282
283
            $errorMessage = array_merge($errorMessage, $messages);
284
            $jobValid = false;
285
        }
286
287
        $errorMessage = '<br />' . implode('<br />', $errorMessage);
288
        if ($isAjax) {
289
            if ($instanceForm instanceof SummaryForm) {
290
                $instanceForm->setRenderMode(SummaryForm::RENDER_SUMMARY);
291
                $viewHelper = 'summaryform';
292
            } else {
293
                $viewHelper = 'form';
294
            }
295
            $viewHelperManager  = $serviceLocator->get('ViewHelperManager');
296
            $content = $viewHelperManager->get($viewHelper)->__invoke($instanceForm);
297
            $viewModel = new JsonModel(
298
                array(
299
                'content' => $content,
300
                'valid' => $valid,
301
                'jobvalid' => $jobValid,
302
                'errors' => $formErrorMessages,
303
                'errorMessage' => $errorMessage)
304
            );
305
        } else {
306
            if ($jobEntity->isDraft()) {
307
                $form->getForm('general.nameForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
308
                $form->getForm('general.portalForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
309
                $locElem = $form->getForm('general.locationForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM)
310
                                ->getBaseFieldset()->get('geoLocation');
311
                if ($locElem instanceof \Geo\Form\GeoText) {
312
                    $loc = $jobEntity->getLocations();
313
                    if (count($loc)) {
314
                        $locElem->setValue($loc->first());
315
                    }
316
                }
317
            } else {
318
                $formEvents->trigger('DisableElements', $this, [ 'form' => $form, 'job'=>$jobEntity ]);
319
                // Job is deployed, some changes are now disabled
320
                $form->enableAll();
321
            }
322
323
324
            $completionLink = $this->url()->fromRoute(
325
                'lang/jobs/completion',
326
                [ 'id' => $jobEntity->getId()]
327
            );
328
329
            $viewModel = $this->getViewModel($form);
330
331
            $viewModel->setVariables(
332
                array(
333
                'completionLink' => $completionLink,
334
                'title' => $jobEntity->getTitle(),
335
                'job' => $jobEntity,
336
                'summary' => 'this is what we charge you for your offer...',
337
                'valid' => $valid,
338
                'jobvalid' => $jobValid,
339
                'errorMessage' => $errorMessage,
340
                'isDraft' => $jobEntity->isDraft()
341
                )
342
            );
343
        }
344
        return $viewModel;
345
    }
346
347
    protected function changeStatus(JobInterface $job, $status)
348
    {
349
        $oldStatus = $job->getStatus();
350
351
        if ($status == $oldStatus->getName()) {
352
            return;
353
        }
354
        $user = $this->auth->getUser();
355
        try {
356
            $job->changeStatus($status, sprintf('Status changed from %s to %s by %s', $oldStatus->getName(), $status, $user->getInfo()->getDisplayName()));
357
358
            $events = $this->serviceLocator->get('Jobs/Events');
359
            $events->trigger(JobEvent::EVENT_STATUS_CHANGED, $this, ['job' => $job, 'status' => $oldStatus]);
360
            $this->notification()->success(/*@translate*/ 'Status successfully changed.');
361
        } catch (\DomainException $e) {
362
            $this->notification()->error(/*@translate*/ 'Change status failed.');
363
        }
364
    }
365
366
    /**
367
     * @return array
368
     */
369
    public function checkApplyIdAction()
370
    {
371
        $services = $this->serviceLocator;
372
        $validator = $services->get('validatormanager')->get('Jobs/Form/UniqueApplyId');
373
        if (!$validator->isValid($this->params()->fromQuery('applyId'))) {
374
            return array(
375
                'ok' => false,
376
                'messages' => $validator->getMessages(),
377
            );
378
        }
379
        return array('ok' => true);
380
    }
381
382
    /**
383
     * @param $job
384
     * @return mixed
385
     */
386
    protected function getFormular($job)
387
    {
388
        $services = $this->serviceLocator;
389
        /* @var $forms \Zend\Form\FormElementManager */
390
        $forms    = $services->get('FormElementManager');
391
        /* @var $container \Jobs\Form\Job */
392
393
        $container = $forms->get(
394
            'Jobs/Job',
395
            array(
396
            'mode' => $job->id ? 'edit' : 'new'
397
            )
398
        );
399
        $container->setEntity($job);
400
        $container->setParam('job', $job->id);
401
        $container->setParam('snapshot', $job instanceOf JobSnapshot ? $job->getSnapshotId() : '');
402
        $container->setParam('applyId', $job->applyId);
403
        return $container;
404
    }
405
406
    /**
407
     * @param $form
408
     * @param array $params
409
     * @return ViewModel
410
     */
411
    protected function getViewModel($form, array $params = array())
412
    {
413
        $variables = array(
414
            'form' => $form,
415
        );
416
        $viewVars  = array_merge($variables, $params);
417
        
418
        $model = new ViewModel($viewVars);
419
        $model->setTemplate("jobs/manage/form");
420
        
421
        return $model;
422
    }
423
424
    /**
425
     * Job opening is completed.
426
     *
427
     * @return array
428
     */
429
    public function completionAction()
430
    {
431
        $serviceLocator = $this->serviceLocator;
432
433
        $job = $this->initializeJob()->get($this->params());
434
435
        if ($job->isDraft()) {
436
437
            $job->setIsDraft(false);
438
439
            $reference = $job->getReference();
440
441
            if (empty($reference)) {
442
                /* @var $repository \Jobs\Repository\Job */
443
                $repository = $this->repositoryService->get('Jobs/Job');
444
                $job->setReference($repository->getUniqueReference());
445
            }
446
            $job->changeStatus(Status::CREATED, "job was created");
447
            $job->setAtsEnabled(true);
448
449
            // sets ATS-Mode on intern
450
            $job->getAtsMode();
451
452
            /*
453
            * make the job opening persist and fire the EVENT_JOB_CREATED
454
            */
455
            $this->repositoryService->store($job);
456
457
            $jobEvents = $serviceLocator->get('Jobs/Events');
458
            $jobEvents->trigger(JobEvent::EVENT_JOB_CREATED, $this, array('job' => $job));
459
        } else if ($job->isActive()) {
460
            $job->getSnapshotMeta()->getEntity()->changeStatus(Status::WAITING_FOR_APPROVAL, 'job was edited.');
461
        }
462
463
        return array('job' => $job);
464
    }
465
466
    /**
467
     * all actions around approve or decline jobs-offers
468
     *
469
     * @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...
470
     */
471
    public function approvalAction()
472
    {
473
        $serviceLocator = $this->serviceLocator;
474
        $user           = $this->auth->getUser();
475
476
        $params         = $this->params('state');
477
478
        $jobEntity = $this->initializeJob()->get($this->params());
479
        $jobEvent       = $serviceLocator->get('Jobs/Event');
480
        $jobEvent->setJobEntity($jobEntity);
481
        $jobEvent->addPortal('XingVendorApi');
482
        $jobEvents      = $serviceLocator->get('Jobs/Events');
483
        // array with differences between the last snapshot and the actual entity
484
        // is remains Null if there is no snapshot
485
        // it will be an empty array if the snapshot and the actual entity do not differ
486
        $diff           = null;
487
488
489
        if ($params == 'declined') {
490
            $jobEntity->changeStatus(Status::REJECTED, sprintf(/*@translate*/ "Job opening was rejected by %s", $user->getInfo()->getDisplayName()));
491
            $jobEntity->setIsDraft(true);
492
            $this->repositoryService->store($jobEntity);
493
            $jobEvents->trigger(JobEvent::EVENT_JOB_REJECTED, $jobEvent);
494
            $this->notification()->success(/*@translate */'Job has been rejected');
495
        }
496
497
        if ($params == 'approved') {
498
            if ($jobEntity instanceOf JobSnapshot) {
499
                $jobEntity = $this->repositoryService->get('Jobs/JobSnapshot')->merge($jobEntity);
500
            } else {
501
                $jobEntity->setDatePublishStart();
502
            }
503
            $jobEntity->changeStatus(Status::ACTIVE, sprintf(/*@translate*/ "Job opening was activated by %s", $user->getInfo()->getDisplayName()));
504
            $this->repositoryService->store($jobEntity);
505
            $jobEvents->trigger(JobEvent::EVENT_JOB_ACCEPTED, $jobEvent);
506
            //$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...
507
            $this->notification()->success(/* @translate */ 'Job has been approved');
508
            return $this->redirect()->toRoute('lang/admin/jobs', array('lang' => $this->params('lang')));
509
        }
510
511
        $query = $jobEntity instanceOf JobSnapshot ? ['snapshot' => $jobEntity->getSnapshotId()] : ['id' => $jobEntity->getId()];
512
        $viewLink = $this->url()->fromRoute(
513
            'lang/jobs/view',
514
            array(),
515
            array('query' => $query
516
                      )
517
        );
518
519
        $approvalLink = $this->url()->fromRoute(
520
            'lang/jobs/approval',
521
            array('state' => 'approved'),
522
            array('query' => $query)
523
        );
524
525
        $declineLink = $this->url()->fromRoute(
526
            'lang/jobs/approval',
527
            array('state' => 'declined'),
528
            array('query' => $query)
529
        );
530
531
        return array('job' => $jobEntity,
532
                     'diffSnapshot' => $diff,
533
                     'viewLink' => $viewLink,
534
                     'approvalLink' => $approvalLink,
535
                     'declineLink' => $declineLink);
536
    }
537
538
    /**
539
     * Deactivate a job posting
540
     *
541
     * @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...
542
     */
543
    public function deactivateAction()
544
    {
545
        $user           = $this->auth->getUser();
546
547
        $jobEntity = $this->initializeJob()->get($this->params());
548
549
        try {
550
            $jobEntity->changeStatus(Status::INACTIVE, sprintf(/*@translate*/ "Job was deactivated by %s", $user->getInfo()->getDisplayName()));
551
            $this->notification()->success(/*@translate*/ 'Job has been deactivated');
552
        } catch (\Exception $e) {
553
            $this->notification()->danger(/*@translate*/ 'Job could not be deactivated');
554
        }
555
        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...
556
    }
557
558
    public function deleteAction()
559
    {
560
        $job = $this->initializeJob()->get($this->params());
561
        $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...
562
563
        $this->repositoryService->remove($job);
564
565
        $this->notification()->success(/*@translate*/ 'Job has been deleted.');
566
        return $this->redirect()->toRoute('lang/jobs');
567
568
    }
569
    /**
570
     * Assign a template to a job posting
571
     *
572
     * @return JsonModel
573
     */
574
    public function templateAction()
575
    {
576
        try {
577
            $jobEntity = $this->initializeJob()->get($this->params());
578
            $jobEntity->setTemplate($this->params('template', 'default'));
579
            $this->repositoryService->store($jobEntity);
580
            $this->notification()->success(/* @translate*/ 'Template changed');
581
        } catch (\Exception $e) {
582
            $this->notification()->danger(/* @translate */ 'Template not changed');
583
        }
584
585
        return new JsonModel(array());
586
    }
587
588
    /**
589
     * @param $script
590
     * @param array $parameter
591
     * @return ViewModel
592
     */
593 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...
594
    {
595
        /** @var Response $response */
596
        $response = $this->getResponse();
597
        $response->setStatusCode(Response::STATUS_CODE_500);
598
599
        $model = new ViewModel($parameter);
600
        $model->setTemplate("jobs/error/$script");
601
602
        return $model;
603
    }
604
605
    public function historyAction()
606
    {
607
        $jobEntity = $this->initializeJob()->get($this->params());
608
        $title          = $jobEntity->getTitle();
609
        $historyEntity  = $jobEntity->getHistory();
610
611
        $model = new ViewModel(array('title' => $title, 'history' => $historyEntity));
612
        $model->setTerminal(true);
613
        return $model;
614
    }
615
}
616