Completed
Push — develop ( 0c9847...b22ed9 )
by
unknown
148:24 queued 129:48
created

ManageController::getFormular()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 18
rs 9.4285
cc 2
eloc 11
nc 1
nop 1
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\Status;
16
use Core\Repository\RepositoryService;
17
use Zend\Mvc\Controller\AbstractActionController;
18
use Zend\View\Model\ViewModel;
19
use Zend\View\Model\JsonModel;
20
use Core\Form\SummaryForm;
21
use Zend\Mvc\MvcEvent;
22
use Jobs\Listener\Events\JobEvent;
23
use Core\Form\SummaryFormInterface;
24
use Zend\Stdlib\ArrayUtils;
25
use Auth\AuthenticationService;
26
use Zend\Mvc\I18n\Translator;
27
use Zend\Http\PhpEnvironment\Response;
28
29
/**
30
 * This Controller handles management actions for jobs.
31
 *
32
 * @method \Acl\Controller\Plugin\Acl acl()
33
 * @method \Jobs\Controller\Plugin\InitializeJob initializeJob()
34
 * @method \Core\Controller\Plugin\Notification notification()
35
 * @method \Core\Controller\Plugin\EntitySnapshot entitySnapshot()
36
 *
37
 * @author Mathias Gelhausen <[email protected]>
38
 */
39
class ManageController extends AbstractActionController
40
{
41
    /**
42
     * @var AuthenticationService
43
     */
44
    protected $auth;
45
46
    /**
47
     * @var RepositoryService
48
     */
49
    protected $repositoryService;
50
51
    /**
52
     * @var Translator
53
     */
54
    protected $translator;
55
56
    /**
57
     * @param AuthenticationService $auth
58
     * @param RepositoryService     $repositoryService
59
     * @param                       $translator
60
     */
61
    public function __construct(AuthenticationService $auth, RepositoryService $repositoryService, Translator $translator)
62
    {
63
        $this->auth = $auth;
64
        $this->repositoryService = $repositoryService;
65
        $this->translator = $translator;
66
    }
67
68
    /**
69
     * @return $this|void
70
     */
71 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...
72
    {
73
        parent::attachDefaultListeners();
74
        $events = $this->getEventManager();
75
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
76
        $serviceLocator = $this->getServiceLocator();
77
        $defaultServices = $serviceLocator->get('DefaultListeners');
78
        $events = $this->getEventManager();
79
        $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...
80
81
        return $this;
82
    }
83
84
    /**
85
     * Dispatch listener callback.
86
     *
87
     * Attaches the MailSender aggregate listener to the job event manager.
88
     *
89
     * @param MvcEvent $e
90
     * @since 0.19
91
     */
92
    public function preDispatch(MvcEvent $e)
93
    {
94
        if ('calculate' == $this->params()->fromQuery('do')) {
95
            return;
96
        }
97
        $routeMatch = $e->getRouteMatch();
98
        $action = $routeMatch->getParam('action');
99
100
        if (in_array($action, array('edit', 'approval', 'completion'))) {
101
            $services = $this->getServiceLocator();
102
            $jobEvents = $services->get('Jobs/Events');
103
            $mailSender = $services->get('Jobs/Listener/MailSender');
104
105
            $mailSender->attach($jobEvents);
106
        }
107
    }
108
109
    /**
110
     *
111
     *
112
     * @return null|ViewModel
113
     */
114
    public function editAction()
115
    {
116
        if ('calculate' == $this->params()->fromQuery('do')) {
117
            $calc = $this->getServiceLocator()->get('filtermanager')->get('Jobs/ChannelPrices');
118
            $sum = $calc->filter($this->params()->fromPost('channels'));
119
120
            return new JsonModel(['sum' => $sum]);
121
        }
122
123
        return $this->save();
124
    }
125
126
    /**
127
     * @return null|ViewModel
128
     */
129
    public function saveAction()
130
    {
131
        return $this->save();
132
    }
133
134
    public function channelListAction()
135
    {
136
        $serviceLocator = $this->getServiceLocator();
137
        $options = $serviceLocator->get('Core/Options');
138
        $channels = $serviceLocator->get('Jobs/Options/Provider');
139
140
141
142
        $jobEntity = $this->initializeJob()->get($this->params());
143
144
        $model = new ViewModel([
145
                                   'portals' => $jobEntity->getPortals(),
146
                                   'channels' => $channels,
147
                                   'defaultCurrencyCode' => $options->defaultCurrencyCode,
148
                                   'defaultTaxRate' =>  $options->defaultTaxRate,
149
                                   'jobId' => $jobEntity->getId()
150
                               ]);
151
        $model->setTemplate('jobs/partials/channel-list')->setTerminal(true);
152
        return $model;
153
    }
154
155
    /**
156
     * save a Job-Post either by a regular request or by an async post (AJAX)
157
     * a mandatory parameter is the ID of the Job
158
     * in case of a regular Request you can
159
     *
160
     * parameter are arbitrary elements for defaults or programming flow
161
     *
162
     * @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...
163
     * @return null|ViewModel
164
     * @throws \RuntimeException
165
     */
166
    protected function save()
167
    {
168
        $serviceLocator     = $this->getServiceLocator();
169
        $formEvents         = $serviceLocator->get('Jobs/JobContainer/Events');
170
171
        $user               = $this->auth->getUser();
172
        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...
173
            return $this->getErrorViewModel('no-parent', array('cause' => 'noEmail'));
174
        }
175
        $userOrg            = $user->getOrganization();
176
        if (!$userOrg->hasAssociation()) {
177
            return $this->getErrorViewModel('no-parent', array('cause' => 'noCompany'));
178
        }
179
180
        /** @var \Zend\Http\Request $request */
181
        $request            = $this->getRequest();
182
        $isAjax             = $request->isXmlHttpRequest();
183
184
        $params             = $this->params();
185
        $formIdentifier     = $params->fromQuery('form');
186
187
        $jobEntity = $this->initializeJob()->get($this->params(), true);
188
189
        $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...
190
        $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...
191
        if ($status = $params->fromQuery('status')) {
192
            $this->changeStatus($jobEntity, $status);
193
        }
194
195
        $form               = $this->getFormular($jobEntity);
196
197
        $valid              = true;
198
        $instanceForm       = null;
199
        $formErrorMessages = array();
200
201
        if (isset($formIdentifier) &&  $request->isPost()) {
202
            // at this point the form get instantiated and immediately accumulated
203
            $instanceForm = $form->getForm($formIdentifier);
204
            if (!isset($instanceForm)) {
205
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
206
            }
207
            // the id may be part of the postData, but it never should be altered
208
            $postData = $request->getPost();
209
            if (isset($postData['id'])) {
210
                unset($postData['id']);
211
            }
212
            unset($postData['applyId']);
213
            $instanceForm->setData($postData);
214
            $valid = $instanceForm->isValid();
215
            $formErrorMessages = ArrayUtils::merge($formErrorMessages, $instanceForm->getMessages());
216
            if ($valid) {
217
                /*
218
                 * @todo This is a workaround for GeoJSON data insertion
219
                 * until we figured out, what we really want it to be.
220
                 */
221
                if ('general.locationForm' == $formIdentifier) {
222
                    $locElem = $instanceForm->getBaseFieldset()->get('geo-location');
223
                    if ($locElem instanceof \Geo\Form\GeoText) {
224
                        $loc = $locElem->getValue('entity');
225
                        $locations = $jobEntity->getLocations();
226
                        if (count($locations)) {
227
                            $locations->clear();
228
                        }
229
                        $locations->add($loc);
230
                        $jobEntity->setLocation($locElem->getValue());
231
                    }
232
                }
233
234
                $title = $jobEntity->getTitle();
235
                $templateTitle = $jobEntity->getTemplateValues()->getTitle();
236
237
                if (empty($templateTitle)) {
238
                    $jobEntity->getTemplateValues()->setTitle($title);
239
                }
240
                $this->repositoryService->persist($jobEntity);
0 ignored issues
show
Documentation Bug introduced by
The method persist does not exist on object<Core\Repository\RepositoryService>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
241
            }
242
        }
243
244
        // validation
245
        $jobValid = true;
246
        $errorMessage = array();
247
        if (empty($jobEntity->getTitle())) {
248
            $jobValid = false;
249
            $errorMessage[] = $this->translator->translate('No Title');
250
        }
251
        if (empty($jobEntity->getLocation())) {
252
            $jobValid = false;
253
            $errorMessage[] = $this->translator->translate('No Location');
254
        }
255
        if (empty($jobEntity->getTermsAccepted())) {
256
            $jobValid = false;
257
            $errorMessage[] = $this->translator->translate('Accept the Terms');
258
        }
259
        $result = $formEvents->trigger('ValidateJob', $this, [ 'form' => $form ]);
260
        foreach ($result as $messages) {
261
            if (!$messages) {
262
                continue;
263
            }
264
            if (!is_array($messages)) {
265
                $messages = [ $messages ];
266
            }
267
268
            $errorMessage = array_merge($errorMessage, $messages);
269
            $jobValid = false;
270
        }
271
272
        $errorMessage = '<br />' . implode('<br />', $errorMessage);
273
        if ($isAjax) {
274
            if ($instanceForm instanceof SummaryForm) {
275
                $instanceForm->setRenderMode(SummaryForm::RENDER_SUMMARY);
276
                $viewHelper = 'summaryform';
277
            } else {
278
                $viewHelper = 'form';
279
            }
280
            $viewHelperManager  = $serviceLocator->get('ViewHelperManager');
281
            $content = $viewHelperManager->get($viewHelper)->__invoke($instanceForm);
282
            $viewModel = new JsonModel(
283
                array(
284
                'content' => $content,
285
                'valid' => $valid,
286
                'jobvalid' => $jobValid,
287
                'errors' => $formErrorMessages,
288
                'errorMessage' => $errorMessage)
289
            );
290
        } else {
291
            if ($jobEntity->isDraft()) {
292
                $form->getForm('general.nameForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
293
                $form->getForm('general.portalForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
294
                $locElem = $form->getForm('general.locationForm')->setDisplayMode(SummaryFormInterface::DISPLAY_FORM)
295
                                ->getBaseFieldset()->get('geo-location');
296
                if ($locElem instanceof \Geo\Form\GeoText) {
297
                    $loc = $jobEntity->getLocations();
298
                    if (count($loc)) {
299
                        $locElem->setValue($loc->first());
300
                    }
301
                }
302
            } else {
303
                $formEvents->trigger('DisableElements', $this, [ 'form' => $form, 'job'=>$jobEntity ]);
304
                // Job is deployed, some changes are now disabled
305
                $form->enableAll();
306
            }
307
308
309
            $completionLink = $this->url()->fromRoute(
310
                'lang/jobs/completion',
311
                [ 'id' => $jobEntity->getId()]
312
            );
313
314
            $viewModel = $this->getViewModel($form);
315
316
            $viewModel->setVariables(
317
                array(
318
                'completionLink' => $completionLink,
319
                'title' => $jobEntity->getTitle(),
320
                'job' => $jobEntity,
321
                'summary' => 'this is what we charge you for your offer...',
322
                'valid' => $valid,
323
                'jobvalid' => $jobValid,
324
                'errorMessage' => $errorMessage,
325
                'isDraft' => $jobEntity->isDraft()
326
                )
327
            );
328
        }
329
        return $viewModel;
330
    }
331
332
    protected function changeStatus(JobInterface $job, $status)
333
    {
334
        $oldStatus = $job->getStatus();
335
336
        if ($status == $oldStatus->getName()) {
0 ignored issues
show
Bug introduced by
The method getName cannot be called on $oldStatus (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
337
            return;
338
        }
339
        $user = $this->auth->getUser();
340
        try {
341
            $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 getName cannot be called on $oldStatus (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Bug introduced by
It seems like you code against a concrete implementation and not the interface Jobs\Entity\JobInterface as the method changeStatus() does only exist in the following implementations of said interface: Jobs\Entity\Job.

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...
342
343
            $events = $this->getServiceLocator()->get('Jobs/Events');
344
            $events->trigger(JobEvent::EVENT_STATUS_CHANGED, $this, ['job' => $job, 'status' => $oldStatus]);
345
            $this->notification()->success(/*@translate*/ 'Status successfully changed.');
346
        } catch (\DomainException $e) {
347
            $this->notification()->error(/*@translate*/ 'Change status failed.');
348
        }
349
    }
350
351
    /**
352
     * @return array
353
     */
354
    public function checkApplyIdAction()
355
    {
356
        $services = $this->getServiceLocator();
357
        $validator = $services->get('validatormanager')->get('Jobs/Form/UniqueApplyId');
358
        if (!$validator->isValid($this->params()->fromQuery('applyId'))) {
359
            return array(
360
                'ok' => false,
361
                'messages' => $validator->getMessages(),
362
            );
363
        }
364
        return array('ok' => true);
365
    }
366
367
    /**
368
     * @param $job
369
     * @return mixed
370
     */
371
    protected function getFormular($job)
372
    {
373
        $services = $this->getServiceLocator();
374
        /* @var $forms \Zend\Form\FormElementManager */
375
        $forms    = $services->get('FormElementManager');
376
        /* @var $container \Jobs\Form\Job */
377
378
        $container = $forms->get(
379
            'Jobs/Job',
380
            array(
381
            'mode' => $job->id ? 'edit' : 'new'
382
            )
383
        );
384
        $container->setEntity($job);
385
        $container->setParam('job', $job->id);
386
        $container->setParam('applyId', $job->applyId);
387
        return $container;
388
    }
389
390
    /**
391
     * @param $form
392
     * @param array $params
393
     * @return ViewModel
394
     */
395
    protected function getViewModel($form, array $params = array())
396
    {
397
        $variables = array(
398
            'form' => $form,
399
        );
400
        $viewVars  = array_merge($variables, $params);
401
        
402
        $model = new ViewModel($viewVars);
403
        $model->setTemplate("jobs/manage/form");
404
        
405
        return $model;
406
    }
407
408
    /**
409
     * Job opening is completed.
410
     *
411
     * @return array
412
     */
413
    public function completionAction()
414
    {
415
        $serviceLocator = $this->getServiceLocator();
416
417
        $job = $this->initializeJob()->get($this->params());
418
419
        $job->setIsDraft(false);
420
421
        $reference = $job->getReference();
422
423
        if (empty($reference)) {
424
            /* @var $repository \Jobs\Repository\Job */
425
            $repository = $this->repositoryService->get('Jobs/Job');
426
            $job->setReference($repository->getUniqueReference());
427
        }
428
        $job->changeStatus(Status::CREATED, "job was created");
429
        $job->setAtsEnabled(true);
430
431
        // sets ATS-Mode on intern
432
        $job->getAtsMode();
433
434
        /*
435
         * make the job opening persist and fire the EVENT_JOB_CREATED
436
         */
437
        $this->repositoryService->store($job);
438
439
        $jobEvents = $serviceLocator->get('Jobs/Events');
440
        $jobEvents->trigger(JobEvent::EVENT_JOB_CREATED, $this, array('job' => $job));
441
442
        return array('job' => $job);
443
    }
444
445
    /**
446
     * all actions around approve or decline jobs-offers
447
     *
448
     * @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...
449
     */
450
    public function approvalAction()
451
    {
452
        $serviceLocator = $this->getServiceLocator();
453
        $user           = $this->auth->getUser();
454
455
        $params         = $this->params('state');
456
457
        $jobEntity = $this->initializeJob()->get($this->params());
458
        $jobEvent       = $serviceLocator->get('Jobs/Event');
459
        $jobEvent->setJobEntity($jobEntity);
460
        $jobEvent->addPortal('XingVendorApi');
461
        $jobEvents      = $serviceLocator->get('Jobs/Events');
462
        // array with differences between the last snapshot and the actual entity
463
        // is remains Null if there is no snapshot
464
        // it will be an empty array if the snapshot and the actual entity do not differ
465
        $diff           = null;
466
        // preliminary difference, contain all differences
467
        $prelDiff = $this->entitySnapshot()->diff($jobEntity);
468
        if (isset($prelDiff)) {
469
            // we want just some Values to be compared
470
            $diff = null;
471
            foreach (array('title', 'organization', 'location',
472
                         'templateValues.qualifications', 'templateValues.requirements', 'templateValues.benefits', 'templateValues.title',
473
                         'templateValues._freeValues.description',
474
                     ) as $prelKey) {
475
                if (array_key_exists($prelKey, $prelDiff)) {
476
                    $diff[$prelKey] = $prelDiff[$prelKey];
477
                }
478
            }
479
        }
480
481
        if ($params == 'declined') {
482
            $jobEntity->changeStatus(Status::REJECTED, sprintf(/*@translate*/ "Job opening was rejected by %s", $user->getInfo()->getDisplayName()));
483
            $jobEntity->setIsDraft(true);
484
            $this->repositoryService->store($jobEntity);
485
            $jobEvents->trigger(JobEvent::EVENT_JOB_REJECTED, $jobEvent);
486
            $this->notification()->success(/*@translate */'Job has been rejected');
487
        }
488
489
        if ($params == 'approved') {
490
            $jobEntity->changeStatus(Status::ACTIVE, sprintf(/*@translate*/ "Job opening was activated by %s", $user->getInfo()->getDisplayName()));
491
            $jobEntity->setDatePublishStart();
492
            $this->repositoryService->store($jobEntity);
493
            $jobEvents->trigger(JobEvent::EVENT_JOB_ACCEPTED, $jobEvent);
494
            $this->entitySnapshot($jobEntity);
0 ignored issues
show
Unused Code introduced by
The call to ManageController::entitySnapshot() 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...
495
            $this->notification()->success(/* @translate */ 'Job has been approved');
496
            return $this->redirect()->toRoute('lang/admin/jobs', array('lang' => $this->params('lang')));
497
        }
498
499
        $viewLink = $this->url()->fromRoute(
500
            'lang/jobs/view',
501
            array(),
502
            array('query' =>
503
                      array( 'id' => $jobEntity->getId()))
504
        );
505
506
        $approvalLink = $this->url()->fromRoute(
507
            'lang/jobs/approval',
508
            array('state' => 'approved'),
509
            array('query' =>
510
                      array( 'id' => $jobEntity->getId()))
511
        );
512
513
        $declineLink = $this->url()->fromRoute(
514
            'lang/jobs/approval',
515
            array('state' => 'declined'),
516
            array('query' =>
517
                      array( 'id' => $jobEntity->getId()))
518
        );
519
520
        return array('job' => $jobEntity,
521
                     'diffSnapshot' => $diff,
522
                     'viewLink' => $viewLink,
523
                     'approvalLink' => $approvalLink,
524
                     'declineLink' => $declineLink);
525
    }
526
527
    /**
528
     * Deactivate a job posting
529
     *
530
     * @return null|ViewModel
531
     */
532
    public function deactivateAction()
533
    {
534
        $user           = $this->auth->getUser();
535
536
        $jobEntity = $this->initializeJob()->get($this->params());
537
538
        try {
539
            $jobEntity->changeStatus(Status::INACTIVE, sprintf(/*@translate*/ "Job was deactivated by %s", $user->getInfo()->getDisplayName()));
540
            $this->notification()->success(/*@translate*/ 'Job has been deactivated');
541
        } catch (\Exception $e) {
542
            $this->notification()->danger(/*@translate*/ 'Job could not be deactivated');
543
        }
544
        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...
545
    }
546
547
    /**
548
     * Assign a template to a job posting
549
     *
550
     * @return JsonModel
551
     */
552
    public function templateAction()
553
    {
554
        try {
555
            $jobEntity = $this->initializeJob()->get($this->params());
556
            $jobEntity->setTemplate($this->params('template', 'default'));
557
            $this->repositoryService->store($jobEntity);
558
            $this->notification()->success(/* @translate*/ 'Template changed');
559
        } catch (\Exception $e) {
560
            $this->notification()->danger(/* @translate */ 'Template not changed');
561
        }
562
563
        return new JsonModel(array());
564
    }
565
566
    /**
567
     * @param $script
568
     * @param array $parameter
569
     * @return ViewModel
570
     */
571 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...
572
    {
573
        /** @var Response $response */
574
        $response = $this->getResponse();
575
        $response->setStatusCode(Response::STATUS_CODE_500);
576
577
        $model = new ViewModel($parameter);
578
        $model->setTemplate("jobs/error/$script");
579
580
        return $model;
581
    }
582
583
    public function historyAction()
584
    {
585
        $jobEntity = $this->initializeJob()->get($this->params());
586
        $title          = $jobEntity->getTitle();
587
        $historyEntity  = $jobEntity->getHistory();
588
589
        $model = new ViewModel(array('title' => $title, 'history' => $historyEntity));
590
        $model->setTerminal(true);
591
        return $model;
592
    }
593
}
594