Completed
Push — develop ( b8a72b...45655e )
by
unknown
29:30
created

ManageController::completionAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 30
rs 8.8571
cc 2
eloc 17
nc 2
nop 0
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 Zend\Mvc\Controller\AbstractActionController;
16
use Zend\View\Model\ViewModel;
17
use Zend\View\Model\JsonModel;
18
use Core\Form\SummaryForm;
19
use Auth\Exception\UnauthorizedAccessException;
20
use Zend\EventManager\EventManagerInterface;
21
use Zend\Mvc\MvcEvent;
22
use Jobs\Listener\Events\JobEvent;
23
use Core\Form\SummaryFormInterface;
24
use Zend\Stdlib\ArrayUtils;
25
26
/**
27
 * This Controller handles management actions for jobs.
28
 *
29
 * @author Mathias Gelhausen <[email protected]>
30
 */
31
class ManageController extends AbstractActionController
32
{
33
34
    /**
35
     * @return $this|void
36
     */
37 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...
38
    {
39
        parent::attachDefaultListeners();
40
        $events = $this->getEventManager();
41
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
42
        $serviceLocator = $this->getServiceLocator();
43
        $defaultServices = $serviceLocator->get('DefaultListeners');
44
        $events = $this->getEventManager();
45
        $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...
46
47
        return $this;
48
    }
49
50
    /**
51
     * Dispatch listener callback.
52
     *
53
     * Attaches the MailSender aggregate listener to the job event manager.
54
     *
55
     * @param MvcEvent $e
56
     * @since 0.19
57
     */
58
    public function preDispatch(MvcEvent $e)
59
    {
60
        if ('calculate' == $this->params()->fromQuery('do')) {
61
            return;
62
        }
63
        $routeMatch = $e->getRouteMatch();
64
        $action = $routeMatch->getParam('action');
65
66
        if (in_array($action, array('edit', 'approval', 'completion'))) {
67
            $services = $this->getServiceLocator();
68
            $jobEvents = $services->get('Jobs/Events');
69
            $mailSender = $services->get('Jobs/Listener/MailSender');
70
71
            $mailSender->attach($jobEvents);
72
        }
73
    }
74
75
    /**
76
     *
77
     */
78
    public function testAction()
79
    {
80
    }
81
82
    /**
83
     * Action called, when a new job should be created.
84
     *
85
     */
86
    public function newAction()
87
    {
88
        $job = $this->getJob(/* create */ true);
89
        $this->acl($job, 'new');
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...
90
        $user = $this->auth()->getUser();
0 ignored issues
show
Documentation Bug introduced by
The method auth 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...
91
        $job->setContactEmail($user->info->email);
92
        $job->setApplyId(
93
            uniqid(substr(md5($user->login), 0, 3))
94
        );
95
        $form  = $this->getFormular($job);
96
        $model = $this->getViewModel($form);
97
        
98
        return $model;
99
    }
100
101
    /**
102
     * @TODO edit-Action and save-Action are doing the same, one of them has to quit
103
     *
104
     * @return null|ViewModel
105
     */
106
    public function editAction()
107
    {
108
        if ('calculate' == $this->params()->fromQuery('do')) {
109
            $calc = $this->getServiceLocator()->get('filtermanager')->get('Jobs/ChannelPrices');
110
            $sum = $calc->filter($this->params()->fromPost('channels'));
111
112
            return new JsonModel(['sum' => $sum]);
113
        }
114
        return $this->save();
115
    }
116
117
    /**
118
     * @return null|ViewModel
119
     */
120
    public function saveAction()
121
    {
122
        return $this->save();
123
    }
124
125
    /**
126
     * save a Job-Post either by a regular request or by an async post (AJAX)
127
     * a mandatory parameter is the ID of the Job
128
     * in case of a regular Request you can
129
     *
130
     * parameter are arbitrary elements for defaults or programming flow
131
     *
132
     * @param array $parameter
133
     * @return null|ViewModel
134
     * @throws \RuntimeException
135
     */
136
    protected function save($parameter = array())
137
    {
138
        $serviceLocator     = $this->getServiceLocator();
139
        $user               = $this->auth()->getUser();
0 ignored issues
show
Documentation Bug introduced by
The method auth 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...
140
        if (empty($user->info->email)) {
141
            return $this->getErrorViewModel('no-parent', array('cause' => 'noEmail'));
142
        }
143
        $userOrg            = $user->getOrganization();
144
        if (!$userOrg->hasAssociation()) {
145
            return $this->getErrorViewModel('no-parent', array('cause' => 'noCompany'));
146
        }
147
        $translator         = $serviceLocator->get('translator');
148
        /** @var \Zend\Http\Request $request */
149
        $request            = $this->getRequest();
150
        $isAjax             = $request->isXmlHttpRequest();
151
        $pageToForm         = array(0 => array('locationForm', 'nameForm', 'portalForm'),
152
                                    1 => array('descriptionForm'),
153
                                    2 => array('previewForm'));
154
        $request            = $this->getRequest();
155
        $params             = $this->params();
156
        $formIdentifier     = $params->fromQuery('form');
157
        $pageIdentifier     = (int) $params->fromQuery('page', array_key_exists('page', $parameter)?$parameter['page']:0);
158
        $jobEntity          = $this->getJob();
159
        $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...
160
        $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...
161
        $form               = $this->getFormular($jobEntity);
162
        //$mvcEvent           = $this->getEvent();
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
163
164
        $valid              = true;
165
        $instanceForm       = null;
166
        $viewHelperManager  = $serviceLocator->get('ViewHelperManager');
167
        $formErrorMessages = array();
168
        if (isset($formIdentifier) &&  $request->isPost()) {
169
            // at this point the form get instantiated and immediately accumulated
170
            $instanceForm = $form->getForm($formIdentifier);
171
            if (!isset($instanceForm)) {
172
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
173
            }
174
            // the id may be part of the postData, but it never should be altered
175
            $postData = $request->getPost();
176
            if (isset($postData['id'])) {
177
                unset($postData['id']);
178
            }
179
            unset($postData['applyId']);
180
            $instanceForm->setData($postData);
181
            $valid = $instanceForm->isValid();
182
            $formErrorMessages = ArrayUtils::merge($formErrorMessages, $instanceForm->getMessages());
183
            if ($valid) {
184
                /*
185
                 * @todo This is a workaround for GeoJSON data insertion
186
                 * until we figured out, what we really want it to be.
187
                 */
188
                if ('locationForm' == $formIdentifier) {
189
                    $locElem = $instanceForm->getBaseFieldset()->get('location');
190
                    if ($locElem instanceOf \Geo\Form\GeoText) {
191
                        $loc = $locElem->getValue('entity');
192
                        $locations = $jobEntity->getLocations();
193
                        if (count($locations)) { $locations->clear(); }
194
                        $locations->add($loc);
195
                        $jobEntity->setLocation($locElem->getValue());
196
                    }
197
                }
198
199
200
                $title = $jobEntity->title;
201
                $templateTitle = $jobEntity->templateValues->title;
202
                if (empty($templateTitle)) {
203
                    $jobEntity->templateValues->title = $title;
204
                }
205
                $serviceLocator->get('repositories')->persist($jobEntity);
206
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
207
            }
208
        }
209
210
        // validation
211
        $jobValid = true;
212
        $errorMessage = array();
213
        if (empty($jobEntity->title)) {
214
            $jobValid = false;
215
            $errorMessage[] = $translator->translate('No Title');
216
        }
217
        if (empty($jobEntity->location)) {
218
            $jobValid = false;
219
            $errorMessage[] = $translator->translate('No Location');
220
        }
221
        if (empty($jobEntity->termsAccepted)) {
222
            $jobValid = false;
223
            $errorMessage[] = $translator->translate('Accept the Terms');
224
        }
225
226
        $errorMessage = '<br />' . implode('<br />', $errorMessage);
227
        if ($isAjax) {
228
            if ($instanceForm instanceof SummaryForm) {
229
                $instanceForm->setRenderMode(SummaryForm::RENDER_SUMMARY);
230
                $viewHelper = 'summaryform';
231
            } else {
232
                $viewHelper = 'form';
233
            }
234
            $content = $viewHelperManager->get($viewHelper)->__invoke($instanceForm);
235
            $viewModel = new JsonModel(
236
                array(
237
                'content' => $content,
238
                'valid' => $valid,
239
                'jobvalid' => $jobValid,
240
                'errors' => $formErrorMessages,
241
                'errorMessage' => $errorMessage)
242
            );
243
        } else {
244
            if (isset($pageIdentifier)) {
245
                $form->disableForm();
246
                if (array_key_exists($pageIdentifier, $pageToForm)) {
247
                    foreach ($pageToForm[$pageIdentifier] as $actualFormIdentifier) {
248
                        $form->enableForm($actualFormIdentifier);
249
                        if ($jobEntity->isDraft()) {
250
                            $actualForm = $form->get($actualFormIdentifier);
251
                            if ('nameForm' != $actualFormIdentifier && $actualForm instanceof SummaryFormInterface) {
252
                                $form->get($actualFormIdentifier)->setDisplayMode(SummaryFormInterface::DISPLAY_FORM);
253
                            }
254
                            if ('locationForm' == $actualFormIdentifier) {
255
                                $locElem = $actualForm->getBaseFieldset()->get('location');
256
                                if ($locElem instanceOf \Geo\Form\GeoText) {
257
                                    $loc = $jobEntity->getLocations();
258
                                    if (count($loc)) {
259
                                        $locElem->setValue($loc->first());
260
                                    }
261
                                }
262
                            }
263
                        }
264
                    }
265
                    if (!$jobEntity->isDraft()) {
266
                        // Job is deployed, some changes are now disabled
267
                        $form->enableAll();
268
                    }
269
                } else {
270
                    throw new \RuntimeException('No form found for page ' . $pageIdentifier);
271
                }
272
            }
273
            $pageLinkNext = null;
274
            $pageLinkPrevious = null;
275 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...
276
                $pageLinkPrevious = $this->url()->fromRoute('lang/jobs/manage', array(), array('query' => array('id' => $jobEntity->id, 'page' => $pageIdentifier - 1)));
277
            }
278 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...
279
                $pageLinkNext     = $this->url()->fromRoute('lang/jobs/manage', array(), array('query' => array('id' => $jobEntity->id, 'page' => $pageIdentifier + 1)));
280
            }
281
            $completionLink = $this->url()->fromRoute('lang/jobs/completion', array('id' => $jobEntity->id));
282
283
            $viewModel = $this->getViewModel($form);
284
            //$viewModel->setVariable('page_next', 1);
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
285
            $viewModel->setVariables(
286
                array(
287
                'pageLinkPrevious' => $pageLinkPrevious,
288
                'pageLinkNext' => $pageLinkNext,
289
                'completionLink' => $completionLink,
290
                'page' => $pageIdentifier,
291
                'title' => $jobEntity->title,
292
                'job' => $jobEntity,
293
                'summary' => 'this is what we charge you for your offer...',
294
                'valid' => $valid,
295
                'jobvalid' => $jobValid,
296
                'errorMessage' => $errorMessage,
297
                'isDraft' => $jobEntity->isDraft()
298
                )
299
            );
300
        }
301
        return $viewModel;
302
    }
303
304
    /**
305
     * @return array
306
     */
307
    public function checkApplyIdAction()
308
    {
309
        $services = $this->getServiceLocator();
310
        $validator = $services->get('validatormanager')->get('Jobs/Form/UniqueApplyId');
311
        if (!$validator->isValid($this->params()->fromQuery('applyId'))) {
312
            return array(
313
                'ok' => false,
314
                'messages' => $validator->getMessages(),
315
            );
316
        }
317
        return array('ok' => true);
318
    }
319
320
    /**
321
     * @param $job
322
     * @return mixed
323
     */
324
    protected function getFormular($job)
325
    {
326
        $services = $this->getServiceLocator();
327
        $forms    = $services->get('FormElementManager');
328
        $container = $forms->get(
329
            'Jobs/Job',
330
            array(
331
            'mode' => $job->id ? 'edit' : 'new'
332
            )
333
        );
334
        $container->setEntity($job);
335
        $container->setParam('job', $job->id);
336
        $container->setParam('applyId', $job->applyId);
337
        return $container;
338
    }
339
340
    /**
341
     * @param bool $allowDraft
342
     * @return \Jobs\Entity\Job|object
343
     * @throws \RuntimeException
344
     */
345
    protected function getJob($allowDraft = true)
346
    {
347
        $services       = $this->getServiceLocator();
348
        $repositories   = $services->get('repositories');
349
        /** @var \Jobs\Repository\Job $repository */
350
        $repository     = $repositories->get('Jobs/Job');
351
        // @TODO three different method to obtain the job-id ?, simplify this
352
        $id_fromRoute   = $this->params('id', 0);
0 ignored issues
show
Coding Style introduced by
$id_fromRoute does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
353
        $id_fromQuery   = $this->params()->fromQuery('id', 0);
0 ignored issues
show
Coding Style introduced by
$id_fromQuery does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
354
        $id_fromSubForm = $this->params()->fromPost('job', 0);
0 ignored issues
show
Coding Style introduced by
$id_fromSubForm does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
355
        $user           = $this->auth()->getUser();
0 ignored issues
show
Documentation Bug introduced by
The method auth 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...
356
        $id             = empty($id_fromRoute)? (empty($id_fromQuery)?$id_fromSubForm:$id_fromQuery) : $id_fromRoute;
0 ignored issues
show
Coding Style introduced by
$id_fromRoute does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
357
358
        if (empty($id) && $allowDraft) {
359
            $this->acl('Jobs/Manage', 'new');
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...
360
            /** @var \Jobs\Entity\Job $job */
361
            $job = $repository->findDraft($user);
362
            if (empty($job)) {
363
                $job = $repository->create();
364
                $job->setIsDraft(true);
365
                $job->setUser($user);
366
                $repositories->store($job);
367
            }
368
            return $job;
369
        }
370
371
        $jobEntity      = $repository->find($id);
372
        if (!$jobEntity) {
373
            throw new \RuntimeException('No job found with id "' . $id . '"');
374
        }
375
        return $jobEntity;
376
    }
377
378
    /**
379
     * @param $form
380
     * @param array $params
381
     * @return ViewModel
382
     */
383
    protected function getViewModel($form, array $params = array())
384
    {
385
        $variables = array(
386
            'form' => $form,
387
        );
388
        $viewVars  = array_merge($variables, $params);
389
        
390
        $model = new ViewModel($viewVars);
391
        $model->setTemplate("jobs/manage/form");
392
        
393
        return $model;
394
    }
395
396
    /**
397
     * Job opening is completed.
398
     *
399
     * @return array
400
     */
401
    public function completionAction()
402
    {
403
404
        $serviceLocator = $this->getServiceLocator();
405
        $jobEntity      = $this->getJob();
406
407
        $jobEntity->isDraft = false;
408
        $reference = $jobEntity->getReference();
409
        if (empty($reference)) {
410
            // create an unique job-reference
411
            $repository = $this->getServiceLocator()
412
                               ->get('repositories')
413
                               ->get('Jobs/Job');
414
            $jobEntity->setReference($repository->getUniqueReference());
415
        }
416
        $jobEntity->changeStatus(Status::CREATED, "job was created");
417
        $jobEntity->atsEnabled = true;
418
        // sets ATS-Mode on intern
419
        $jobEntity->getAtsMode();
420
421
        /*
422
         * make the job opening persist and fire the EVENT_JOB_CREATED
423
         */
424
        $serviceLocator->get('repositories')->store($jobEntity);
425
426
        $jobEvents = $serviceLocator->get('Jobs/Events');
427
        $jobEvents->trigger(JobEvent::EVENT_JOB_CREATED, $this, array('job' => $jobEntity));
428
429
        return array('job' => $jobEntity);
430
    }
431
432
    /**
433
     * all actions around approve or decline jobs-offers
434
     *
435
     * @return array with the viewVariables
436
     */
437
    public function approvalAction()
438
    {
439
440
        $serviceLocator = $this->getServiceLocator();
441
        $translator     = $serviceLocator->get('translator');
442
        $user           = $this->auth()->getUser();
0 ignored issues
show
Documentation Bug introduced by
The method auth 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...
443
        $repositories   = $serviceLocator->get('repositories');
444
        $params         = $this->params('state');
445
        /** @var \Jobs\Entity\Job $jobEntity */
446
        $jobEntity      = $this->getJob();
447
        $jobEvent       = $serviceLocator->get('Jobs/Event');
448
        $jobEvent->setJobEntity($jobEntity);
449
        $jobEvents      = $serviceLocator->get('Jobs/Events');
450
        // array with differences between the last snapshot and the actual entity
451
        // is remains Null if there is no snapshot
452
        // it will be an empty array if the snapshot and the actual entity do not differ
453
        $diff           = null;
454
        // preliminary difference, contain all differences
455
        $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...
456
        if (isset($prelDiff)) {
457
            // we want just some Values to be compared
458
            $diff = null;
459
            foreach (array('title', 'organization', 'location',
460
                         'templateValues.qualifications', 'templateValues.requirements', 'templateValues.benefits', 'templateValues.title',
461
                         'templateValues._freeValues.description',
462
                     ) as $prelKey) {
463
                if (array_key_exists($prelKey, $prelDiff)) {
464
                    $diff[$prelKey] = $prelDiff[$prelKey];
465
                }
466
            }
467
        }
468
469 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...
470
            $jobEntity->changeStatus(Status::REJECTED, sprintf(/*@translate*/ "Job opening was rejected by %s", $user->info->displayName));
471
            $jobEntity->isDraft = true;
0 ignored issues
show
Documentation introduced by
The property $isDraft is declared protected in Jobs\Entity\Job. Since you implemented __set(), maybe consider adding a @property or @property-write 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...
472
            $repositories->store($jobEntity);
473
            $jobEvents->trigger(JobEvent::EVENT_JOB_REJECTED, $jobEvent);
474
            $this->notification()->success($translator->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...
475
        }
476
477 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...
478
            $jobEntity->changeStatus(Status::ACTIVE, sprintf(/*@translate*/ "Job opening was activated by %s", $user->info->displayName));
479
            $repositories->store($jobEntity);
480
            $jobEvents->trigger(JobEvent::EVENT_JOB_ACCEPTED, $jobEvent);
481
            $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...
482
            $this->notification()->success($translator->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...
483
        }
484
485
        $viewLink = $this->url()->fromRoute(
486
            'lang/jobs/view',
487
            array(),
488
            array('query' =>
489
                      array( 'id' => $jobEntity->id))
0 ignored issues
show
Documentation introduced by
The property $id is declared protected in Core\Entity\AbstractIdentifiableEntity. 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...
490
        );
491
492
        $approvalLink = $this->url()->fromRoute(
493
            'lang/jobs/approval',
494
            array('state' => 'approved'),
495
            array('query' =>
496
                      array( 'id' => $jobEntity->id))
0 ignored issues
show
Documentation introduced by
The property $id is declared protected in Core\Entity\AbstractIdentifiableEntity. 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...
497
        );
498
499
        $declineLink = $this->url()->fromRoute(
500
            'lang/jobs/approval',
501
            array('state' => 'declined'),
502
            array('query' =>
503
                      array( 'id' => $jobEntity->id))
0 ignored issues
show
Documentation introduced by
The property $id is declared protected in Core\Entity\AbstractIdentifiableEntity. 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...
504
        );
505
506
        return array('job' => $jobEntity,
507
                     'diffSnapshot' => $diff,
508
                     'viewLink' => $viewLink,
509
                     'approvalLink' => $approvalLink,
510
                     'declineLink' => $declineLink);
511
    }
512
513
    /**
514
     * @return null|ViewModel
515
     */
516
    public function deactivateAction()
517
    {
518
        $serviceLocator = $this->getServiceLocator();
519
        $translator     = $serviceLocator->get('translator');
520
        $user           = $this->auth()->getUser();
0 ignored issues
show
Documentation Bug introduced by
The method auth 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...
521
        $jobEntity      = $this->getJob();
522
523
        try {
524
            $jobEntity->changeStatus(Status::INACTIVE, sprintf(/*@translate*/ "Job was deactivated by %s", $user->info->displayName));
525
            $this->notification()->success($translator->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...
526
        } catch (\Exception $e) {
527
            $this->notification()->danger($translator->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...
528
        }
529
        return $this->save(array('page' => 2));
530
    }
531
532
    /**
533
     * @return JsonModel
534
     */
535
    public function templateAction()
536
    {
537
        $serviceLocator          = $this->getServiceLocator();
538
        $translator          = $serviceLocator->get('translator');
539
        try {
540
            $jobEntity           = $this->getJob();
541
            $template            = $this->params('template', 'default');
542
            $repositories        = $serviceLocator->get('repositories');
543
544
            $jobEntity->template = $template;
545
            $repositories->store($jobEntity);
546
            $this->notification()->success($translator->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...
547
        } catch (\Exception $e) {
548
            $this->notification()->danger($translator->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...
549
        }
550
551
        return new JsonModel(array());
552
    }
553
554
    /**
555
     * @param $script
556
     * @param array $parameter
557
     * @return ViewModel
558
     */
559
    protected function getErrorViewModel($script, $parameter = array())
560
    {
561
        $this->getResponse()->setStatusCode(500);
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...
562
563
        $model = new ViewModel($parameter);
564
        $model->setTemplate("jobs/error/$script");
565
566
        return $model;
567
    }
568
569
    public function historyAction()
570
    {
571
        $serviceLocator = $this->getServiceLocator();
0 ignored issues
show
Unused Code introduced by
$serviceLocator 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...
572
        $jobEntity      = $this->getJob();
573
        $title          = $jobEntity->title;
574
        $historyEntity  = $jobEntity->history;
575
576
        $model = new ViewModel(array('title' => $title, 'history' => $historyEntity));
577
        $model->setTerminal(true);
578
        return $model;
579
    }
580
}
581