Completed
Push — develop ( 5260e4...ed74ca )
by
unknown
23:10 queued 12:19
created

ManageController::save()   F

Complexity

Conditions 30
Paths 2283

Size

Total Lines 186
Code Lines 127

Duplication

Lines 21
Ratio 11.29 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 21
loc 186
rs 2
cc 30
eloc 127
nc 2283
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * YAWIK
5
 *
6
 * @filesource
7
 * @copyright (c) 2013-2015 Cross Solution (http://cross-solution.de)
8
 * @license   MIT
9
 */
10
11
/** ActionController of Core */
12
namespace Jobs\Controller;
13
14
use Jobs\Entity\Status;
15
use Core\Repository\RepositoryService;
16
use Zend\Mvc\Controller\AbstractActionController;
17
use Zend\View\Model\ViewModel;
18
use Zend\View\Model\JsonModel;
19
use Core\Form\SummaryForm;
20
use Zend\Mvc\MvcEvent;
21
use Jobs\Listener\Events\JobEvent;
22
use Core\Form\SummaryFormInterface;
23
use Zend\Stdlib\ArrayUtils;
24
use Auth\AuthenticationService;
25
use Zend\Mvc\I18n\Translator;
26
use Zend\Http\PhpEnvironment\Response;
27
28
/**
29
 * This Controller handles management actions for jobs.
30
 *
31
 * @method \Acl\Controller\Plugin\Acl acl
32
 * @method \Jobs\Controller\Plugin\InitializeJob initializeJob
33
 * @method \Core\Controller\Plugin\Notification notification
34
 * @method \Core\Controller\Plugin\EntitySnapshot entitySnapshot
35
 *
36
 * @author Mathias Gelhausen <[email protected]>
37
 */
38
class ManageController extends AbstractActionController
39
{
40
    /**
41
     * @var AuthenticationService
42
     */
43
    protected $auth;
44
45
    /**
46
     * @var RepositoryService
47
     */
48
    protected $repositoryService;
49
50
    /**
51
     * @var Translator
52
     */
53
    protected $translator;
54
55
    /**
56
     * @param AuthenticationService $auth
57
     * @param RepositoryService     $repositoryService
58
     * @param                       $translator
59
     */
60
    public function __construct(AuthenticationService $auth, RepositoryService $repositoryService, Translator $translator) {
61
        $this->auth = $auth;
62
        $this->repositoryService = $repositoryService;
63
        $this->translator = $translator;
64
    }
65
66
    /**
67
     * @return $this|void
68
     */
69 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...
70
    {
71
        parent::attachDefaultListeners();
72
        $events = $this->getEventManager();
73
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
74
        $serviceLocator = $this->getServiceLocator();
75
        $defaultServices = $serviceLocator->get('DefaultListeners');
76
        $events = $this->getEventManager();
77
        $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...
78
79
        return $this;
80
    }
81
82
    /**
83
     * Dispatch listener callback.
84
     *
85
     * Attaches the MailSender aggregate listener to the job event manager.
86
     *
87
     * @param MvcEvent $e
88
     * @since 0.19
89
     */
90
    public function preDispatch(MvcEvent $e)
91
    {
92
        if ('calculate' == $this->params()->fromQuery('do')) {
93
            return;
94
        }
95
        $routeMatch = $e->getRouteMatch();
96
        $action = $routeMatch->getParam('action');
97
98
        if (in_array($action, array('edit', 'approval', 'completion'))) {
99
            $services = $this->getServiceLocator();
100
            $jobEvents = $services->get('Jobs/Events');
101
            $mailSender = $services->get('Jobs/Listener/MailSender');
102
103
            $mailSender->attach($jobEvents);
104
        }
105
    }
106
107
    /**
108
     * @TODO edit-Action and save-Action are doing the same, one of them has to quit
109
     *
110
     * @return null|ViewModel
111
     */
112
    public function editAction()
113
    {
114
        if ('calculate' == $this->params()->fromQuery('do')) {
115
            $calc = $this->getServiceLocator()->get('filtermanager')->get('Jobs/ChannelPrices');
116
            $sum = $calc->filter($this->params()->fromPost('channels'));
117
118
            return new JsonModel(['sum' => $sum]);
119
        }
120
        return $this->save();
121
    }
122
123
    /**
124
     * @return null|ViewModel
125
     */
126
    public function saveAction()
127
    {
128
        return $this->save();
129
    }
130
131
    /**
132
     * save a Job-Post either by a regular request or by an async post (AJAX)
133
     * a mandatory parameter is the ID of the Job
134
     * in case of a regular Request you can
135
     *
136
     * parameter are arbitrary elements for defaults or programming flow
137
     *
138
     * @param array $parameter
139
     * @return null|ViewModel
140
     * @throws \RuntimeException
141
     */
142
    protected function save($parameter = array())
143
    {
144
        $serviceLocator     = $this->getServiceLocator();
145
        $user               = $this->auth->getUser();
146
        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...
147
            return $this->getErrorViewModel('no-parent', array('cause' => 'noEmail'));
148
        }
149
        $userOrg            = $user->getOrganization();
150
        if (!$userOrg->hasAssociation()) {
151
            return $this->getErrorViewModel('no-parent', array('cause' => 'noCompany'));
152
        }
153
154
        /** @var \Zend\Http\Request $request */
155
        $request            = $this->getRequest();
156
        $isAjax             = $request->isXmlHttpRequest();
157
        $pageToForm         = array(0 => array('locationForm', 'nameForm', 'portalForm'),
158
                                    1 => array('descriptionForm'),
159
                                    2 => array('previewForm'));
160
161
        $params             = $this->params();
162
        $formIdentifier     = $params->fromQuery('form');
163
        $pageIdentifier     = (int) $params->fromQuery('page', array_key_exists('page', $parameter)?$parameter['page']:0);
164
165
        $jobEntity = $this->initializeJob()->get($this->params(), true);
0 ignored issues
show
Documentation Bug introduced by
The method initializeJob does not exist on object<Jobs\Controller\ManageController>? 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...
166
167
        $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...
168
        $this->acl($jobEntity, 'edit');
0 ignored issues
show
Documentation Bug introduced by
The method acl does not exist on object<Jobs\Controller\ManageController>? 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...
169
        $form               = $this->getFormular($jobEntity);
170
171
        $valid              = true;
172
        $instanceForm       = null;
173
        $formErrorMessages = array();
174
175
        if (isset($formIdentifier) &&  $request->isPost()) {
176
            // at this point the form get instantiated and immediately accumulated
177
            $instanceForm = $form->getForm($formIdentifier);
178
            if (!isset($instanceForm)) {
179
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
180
            }
181
            // the id may be part of the postData, but it never should be altered
182
            $postData = $request->getPost();
183
            if (isset($postData['id'])) {
184
                unset($postData['id']);
185
            }
186
            unset($postData['applyId']);
187
            $instanceForm->setData($postData);
188
            $valid = $instanceForm->isValid();
189
            $formErrorMessages = ArrayUtils::merge($formErrorMessages, $instanceForm->getMessages());
190
            if ($valid) {
191
                /*
192
                 * @todo This is a workaround for GeoJSON data insertion
193
                 * until we figured out, what we really want it to be.
194
                 */
195
                if ('locationForm' == $formIdentifier) {
196
                    $locElem = $instanceForm->getBaseFieldset()->get('location');
197
                    if ($locElem instanceOf \Geo\Form\GeoText) {
198
                        $loc = $locElem->getValue('entity');
199
                        $locations = $jobEntity->getLocations();
200
                        if (count($locations)) { $locations->clear(); }
201
                        $locations->add($loc);
202
                        $jobEntity->setLocation($locElem->getValue());
203
                    }
204
                }
205
206
                $title = $jobEntity->getTitle();
207
                $templateTitle = $jobEntity->getTemplateValues()->getTitle();
208
209
                if (empty($templateTitle)) {
210
                    $jobEntity->getTemplateValues()->setTitle($title);
211
                }
212
                $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...
213
            }
214
        }
215
216
        // validation
217
        $jobValid = true;
218
        $errorMessage = array();
219
        if (empty($jobEntity->getTitle())) {
220
            $jobValid = false;
221
            $errorMessage[] = $this->translator->translate('No Title');
222
        }
223
        if (empty($jobEntity->getLocation())) {
224
            $jobValid = false;
225
            $errorMessage[] = $this->translator->translate('No Location');
226
        }
227
        if (empty($jobEntity->getTermsAccepted())) {
228
            $jobValid = false;
229
            $errorMessage[] = $this->translator->translate('Accept the Terms');
230
        }
231
232
        $errorMessage = '<br />' . implode('<br />', $errorMessage);
233
        if ($isAjax) {
234
            if ($instanceForm instanceof SummaryForm) {
235
                $instanceForm->setRenderMode(SummaryForm::RENDER_SUMMARY);
236
                $viewHelper = 'summaryform';
237
            } else {
238
                $viewHelper = 'form';
239
            }
240
            $viewHelperManager  = $serviceLocator->get('ViewHelperManager');
241
            $content = $viewHelperManager->get($viewHelper)->__invoke($instanceForm);
242
            $viewModel = new JsonModel(
243
                array(
244
                'content' => $content,
245
                'valid' => $valid,
246
                'jobvalid' => $jobValid,
247
                'errors' => $formErrorMessages,
248
                'errorMessage' => $errorMessage)
249
            );
250
        } else {
251
            if (isset($pageIdentifier)) {
252
                $form->disableForm();
253
                if (array_key_exists($pageIdentifier, $pageToForm)) {
254
                    foreach ($pageToForm[$pageIdentifier] as $actualFormIdentifier) {
255
                        $form->enableForm($actualFormIdentifier);
256
                        if ($jobEntity->isDraft()) {
257
                            $actualForm = $form->get($actualFormIdentifier);
258
                            if ('nameForm' != $actualFormIdentifier && $actualForm instanceof SummaryFormInterface) {
259
                                $form->get($actualFormIdentifier)->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Form\ElementInterface as the method setDisplayMode() does only exist in the following implementations of said interface: Applications\Form\Base, Applications\Form\Facts, Auth\Form\UserBase, Auth\Form\UserInfo, Core\Form\SummaryForm, Jobs\Form\AtsMode, Jobs\Form\Base, Jobs\Form\CompanyName, Jobs\Form\Multipost, Organizations\Form\Employees, Organizations\Form\OrganizationsContactForm, Organizations\Form\OrganizationsDescriptionForm, Organizations\Form\OrganizationsNameForm.

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...
260
                            }
261
                            if ('locationForm' == $actualFormIdentifier) {
262
                                $locElem = $actualForm->getBaseFieldset()->get('location');
263
                                if ($locElem instanceOf \Geo\Form\GeoText) {
264
                                    $loc = $jobEntity->getLocations();
265
                                    if (count($loc)) {
266
                                        $locElem->setValue($loc->first());
267
                                    }
268
                                }
269
                            }
270
                        }
271
                    }
272
                    if (!$jobEntity->isDraft()) {
273
                        // Job is deployed, some changes are now disabled
274
                        $form->enableAll();
275
                    }
276
                } else {
277
                    throw new \RuntimeException('No form found for page ' . $pageIdentifier);
278
                }
279
            }
280
            $pageLinkNext = null;
281
            $pageLinkPrevious = null;
282 View Code Duplication
            if (0 < $pageIdentifier) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
283
                $pageLinkPrevious = $this->url()->fromRoute(
284
                    'lang/jobs/manage',
285
                    [],
286
                    ['query' => [
287
                        'id' => $jobEntity->getId(),
288
                        'page' => $pageIdentifier - 1]
289
                    ]
290
                );
291
            }
292 View Code Duplication
            if ($pageIdentifier < count($pageToForm) - 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
293
                $pageLinkNext     = $this->url()->fromRoute(
294
                    'lang/jobs/manage',
295
                    [],
296
                    [
297
                        'query' => [
298
                            'id' => $jobEntity->getId(),
299
                            'page' => $pageIdentifier + 1]
300
                    ]
301
                );
302
            }
303
            $completionLink = $this->url()->fromRoute(
304
                'lang/jobs/completion',
305
                [ 'id' => $jobEntity->getId()]
306
            );
307
308
            $viewModel = $this->getViewModel($form);
309
310
            $viewModel->setVariables(
311
                array(
312
                'pageLinkPrevious' => $pageLinkPrevious,
313
                'pageLinkNext' => $pageLinkNext,
314
                'completionLink' => $completionLink,
315
                'page' => $pageIdentifier,
316
                'title' => $jobEntity->title,
317
                'job' => $jobEntity,
318
                'summary' => 'this is what we charge you for your offer...',
319
                'valid' => $valid,
320
                'jobvalid' => $jobValid,
321
                'errorMessage' => $errorMessage,
322
                'isDraft' => $jobEntity->isDraft()
323
                )
324
            );
325
        }
326
        return $viewModel;
327
    }
328
329
    /**
330
     * @return array
331
     */
332
    public function checkApplyIdAction()
333
    {
334
        $services = $this->getServiceLocator();
335
        $validator = $services->get('validatormanager')->get('Jobs/Form/UniqueApplyId');
336
        if (!$validator->isValid($this->params()->fromQuery('applyId'))) {
337
            return array(
338
                'ok' => false,
339
                'messages' => $validator->getMessages(),
340
            );
341
        }
342
        return array('ok' => true);
343
    }
344
345
    /**
346
     * @param $job
347
     * @return mixed
348
     */
349
    protected function getFormular($job)
350
    {
351
        $services = $this->getServiceLocator();
352
        /* @var $forms \Zend\Form\FormElementManager */
353
        $forms    = $services->get('FormElementManager');
354
        /* @var $container \Jobs\Form\Job */
355
        $container = $forms->get(
356
            'Jobs/Job',
357
            array(
358
            'mode' => $job->id ? 'edit' : 'new'
359
            )
360
        );
361
        $container->setEntity($job);
362
        $container->setParam('job', $job->id);
363
        $container->setParam('applyId', $job->applyId);
364
        return $container;
365
    }
366
367
    /**
368
     * @param $form
369
     * @param array $params
370
     * @return ViewModel
371
     */
372
    protected function getViewModel($form, array $params = array())
373
    {
374
        $variables = array(
375
            'form' => $form,
376
        );
377
        $viewVars  = array_merge($variables, $params);
378
        
379
        $model = new ViewModel($viewVars);
380
        $model->setTemplate("jobs/manage/form");
381
        
382
        return $model;
383
    }
384
385
    /**
386
     * Job opening is completed.
387
     *
388
     * @return array
389
     */
390
    public function completionAction()
391
    {
392
        $serviceLocator = $this->getServiceLocator();
393
394
        $job = $this->initializeJob()->get($this->params());
0 ignored issues
show
Documentation Bug introduced by
The method initializeJob does not exist on object<Jobs\Controller\ManageController>? 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...
395
396
        $job->setIsDraft(false);
397
398
        $reference = $job->getReference();
399
400
        if (empty($reference)) {
401
            /* @var $repository \Jobs\Repository\Job */
402
            $repository = $this->repositoryService->get('Jobs/Job');
403
            $job->setReference($repository->getUniqueReference());
404
        }
405
        $job->changeStatus(Status::CREATED, "job was created");
406
        $job->setAtsEnabled(true);
407
408
        // sets ATS-Mode on intern
409
        $job->getAtsMode();
410
411
        /*
412
         * make the job opening persist and fire the EVENT_JOB_CREATED
413
         */
414
        $this->repositoryService->store($job);
415
416
        $jobEvents = $serviceLocator->get('Jobs/Events');
417
        $jobEvents->trigger(JobEvent::EVENT_JOB_CREATED, $this, array('job' => $job));
418
419
        return array('job' => $job);
420
    }
421
422
    /**
423
     * all actions around approve or decline jobs-offers
424
     *
425
     * @return array with the viewVariables
426
     */
427
    public function approvalAction()
428
    {
429
        $serviceLocator = $this->getServiceLocator();
430
        $user           = $this->auth->getUser();
431
432
        $params         = $this->params('state');
433
434
        $jobEntity = $this->initializeJob()->get($this->params());
0 ignored issues
show
Documentation Bug introduced by
The method initializeJob does not exist on object<Jobs\Controller\ManageController>? 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...
435
        $jobEvent       = $serviceLocator->get('Jobs/Event');
436
        $jobEvent->setJobEntity($jobEntity);
437
        $jobEvents      = $serviceLocator->get('Jobs/Events');
438
        // array with differences between the last snapshot and the actual entity
439
        // is remains Null if there is no snapshot
440
        // it will be an empty array if the snapshot and the actual entity do not differ
441
        $diff           = null;
442
        // preliminary difference, contain all differences
443
        $prelDiff = $this->entitySnapshot()->diff($jobEntity);
0 ignored issues
show
Documentation Bug introduced by
The method entitySnapshot does not exist on object<Jobs\Controller\ManageController>? 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...
444
        if (isset($prelDiff)) {
445
            // we want just some Values to be compared
446
            $diff = null;
447
            foreach (array('title', 'organization', 'location',
448
                         'templateValues.qualifications', 'templateValues.requirements', 'templateValues.benefits', 'templateValues.title',
449
                         'templateValues._freeValues.description',
450
                     ) as $prelKey) {
451
                if (array_key_exists($prelKey, $prelDiff)) {
452
                    $diff[$prelKey] = $prelDiff[$prelKey];
453
                }
454
            }
455
        }
456
457 View Code Duplication
        if ($params == 'declined') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
458
            $jobEntity->changeStatus(Status::REJECTED, sprintf(/*@translate*/ "Job opening was rejected by %s", $user->getInfo()->getDisplayName()));
459
            $jobEntity->setIsDraft(true);
460
            $this->repositoryService->store($jobEntity);
461
            $jobEvents->trigger(JobEvent::EVENT_JOB_REJECTED, $jobEvent);
462
            $this->notification()->success(/*@translate */'Job has been rejected');
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Jobs\Controller\ManageController>? 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...
463
        }
464
465 View Code Duplication
        if ($params == 'approved') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
466
            $jobEntity->changeStatus(Status::ACTIVE, sprintf(/*@translate*/ "Job opening was activated by %s", $user->getInfo()->getDisplayName()));
467
            $this->repositoryService->store($jobEntity);
468
            $jobEvents->trigger(JobEvent::EVENT_JOB_ACCEPTED, $jobEvent);
469
            $this->entitySnapshot($jobEntity);
0 ignored issues
show
Documentation Bug introduced by
The method entitySnapshot does not exist on object<Jobs\Controller\ManageController>? 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...
470
            $this->notification()->success(/* @translate */ 'Job has been approved');
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Jobs\Controller\ManageController>? 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...
471
        }
472
473
        $viewLink = $this->url()->fromRoute(
474
            'lang/jobs/view',
475
            array(),
476
            array('query' =>
477
                      array( 'id' => $jobEntity->getId()))
478
        );
479
480
        $approvalLink = $this->url()->fromRoute(
481
            'lang/jobs/approval',
482
            array('state' => 'approved'),
483
            array('query' =>
484
                      array( 'id' => $jobEntity->getId()))
485
        );
486
487
        $declineLink = $this->url()->fromRoute(
488
            'lang/jobs/approval',
489
            array('state' => 'declined'),
490
            array('query' =>
491
                      array( 'id' => $jobEntity->getId()))
492
        );
493
494
        return array('job' => $jobEntity,
495
                     'diffSnapshot' => $diff,
496
                     'viewLink' => $viewLink,
497
                     'approvalLink' => $approvalLink,
498
                     'declineLink' => $declineLink);
499
    }
500
501
    /**
502
     * Deactivate a job posting
503
     *
504
     * @return null|ViewModel
505
     */
506
    public function deactivateAction()
507
    {
508
        $user           = $this->auth->getUser();
509
510
        $jobEntity = $this->initializeJob()->get($this->params());
0 ignored issues
show
Documentation Bug introduced by
The method initializeJob does not exist on object<Jobs\Controller\ManageController>? 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...
511
512
        try {
513
            $jobEntity->changeStatus(Status::INACTIVE, sprintf(/*@translate*/ "Job was deactivated by %s", $user->getInfo()->getDisplayName()));
514
            $this->notification()->success(/*@translate*/ 'Job has been deactivated');
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Jobs\Controller\ManageController>? 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...
515
        } catch (\Exception $e) {
516
            $this->notification()->danger(/*@translate*/ 'Job could not be deactivated');
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Jobs\Controller\ManageController>? 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...
517
        }
518
        return $this->save(array('page' => 2));
519
    }
520
521
    /**
522
     * Assign a template to a job posting
523
     *
524
     * @return JsonModel
525
     */
526
    public function templateAction()
527
    {
528
        try {
529
            $jobEntity = $this->initializeJob()->get($this->params());
0 ignored issues
show
Documentation Bug introduced by
The method initializeJob does not exist on object<Jobs\Controller\ManageController>? 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...
530
            $jobEntity->setTemplate($this->params('template', 'default'));
531
            $this->repositoryService->store($jobEntity);
532
            $this->notification()->success(/* @translate*/ 'Template changed');
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Jobs\Controller\ManageController>? 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...
533
        } catch (\Exception $e) {
534
            $this->notification()->danger(/* @translate */ 'Template not changed');
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Jobs\Controller\ManageController>? 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...
535
        }
536
537
        return new JsonModel(array());
538
    }
539
540
    /**
541
     * @param $script
542
     * @param array $parameter
543
     * @return ViewModel
544
     */
545 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...
546
    {
547
        /** @var Response $response */
548
        $response = $this->getResponse();
549
        $response->setStatusCode(Response::STATUS_CODE_500);
550
551
        $model = new ViewModel($parameter);
552
        $model->setTemplate("jobs/error/$script");
553
554
        return $model;
555
    }
556
557
    public function historyAction()
558
    {
559
        $jobEntity = $this->initializeJob()->get($this->params());
0 ignored issues
show
Documentation Bug introduced by
The method initializeJob does not exist on object<Jobs\Controller\ManageController>? 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...
560
        $title          = $jobEntity->getTitle();
561
        $historyEntity  = $jobEntity->getHistory();
562
563
        $model = new ViewModel(array('title' => $title, 'history' => $historyEntity));
564
        $model->setTerminal(true);
565
        return $model;
566
    }
567
}