Passed
Push — master ( 240c83...03f39b )
by Mathias
06:41
created

ApplyController::processAction()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 57
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 57
ccs 0
cts 47
cp 0
rs 8.6257
c 0
b 0
f 0
cc 6
nc 10
nop 0
crap 42

How to fix   Long Method   

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
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright https://yawik.org/COPYRIGHT.php
7
 * @license   MIT
8
 */
9
10
/** Applications controllers */
11
namespace Applications\Controller;
12
13
use Acl\Controller\Plugin\Acl;
14
use Applications\Entity\Attachment;
15
use Applications\Entity\Contact;
16
use Applications\Entity\Settings;
17
use Applications\Form\Apply;
18
use Applications\Listener\Events\ApplicationEvent;
19
use Applications\Service\UploadHandler;
20
use Auth\Controller\Plugin\Auth;
21
use Auth\Entity\SocialProfiles\AbstractProfile;
22
use Auth\Form\UserInfo;
23
use Core\Controller\Plugin\Mailer;
24
use Core\Controller\Plugin\Notification;
25
use Core\EventManager\EventManager;
26
use Core\Factory\ContainerAwareInterface;
27
use Core\Repository\RepositoryService;
28
use Doctrine\MongoDB\GridFSFile;
0 ignored issues
show
Bug introduced by
The type Doctrine\MongoDB\GridFSFile was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
use Exception;
30
use Hybrid_User_Profile;
31
use Interop\Container\ContainerInterface;
32
use Jobs\Repository\Job;
33
use Laminas\Http\Client;
34
use Laminas\Http\Request;
35
use Laminas\Mvc\Controller\AbstractActionController;
36
use Laminas\Mvc\MvcEvent;
37
use Applications\Entity\Application;
38
use Laminas\Validator\ValidatorPluginManager;
39
use Laminas\View\HelperPluginManager;
40
use Laminas\View\Model\ViewModel;
41
use Laminas\View\Model\JsonModel;
42
use Core\Form\Container;
43
use Core\Form\SummaryForm;
44
use Core\Entity\PermissionsInterface;
45
use Applications\Entity\Status;
46
use Organizations\ImageFileCache\Manager as OrganizationImageCacheManager;
47
use RuntimeException;
48
49
/**
50
 * there are basically two ways to use this controller,
51
 * (1) either you have a form, and want to accumulate inputs, or you want to create a form on an existing or new application
52
 * (2) or want to do some action on a concrete form.
53
 *
54
 * for both you need the applyId, which is NOT the application-id, the applyId is an alias for the Job, it can be some human-readable text or an external ID.
55
 * the application to an applyId is found by the combination of the user and the job, that is represented by the applyId.
56
 * this approach ensures, that applications stick to the related job.
57
 *
58
 * nonetheless, there is an exception, for the posts for updating the application, the application-id is needed.
59
 *
60
 * if you use the do as query-parameter, you have to customize the do-Action for the special purpose that is assigned to the do parameter in the query
61
 *
62
 * @method Acl acl()
63
 * @method Notification notification()
64
 * @method Mailer mailer()
65
 * @method Auth auth()
66
 * @author Mathias Gelhausen <[email protected]>
67
 * @author Anthonius Munthi <[email protected]>
68
 */
69
class ApplyController extends AbstractActionController
70
{
71
72
    protected $formContainer;
73
74
    protected array $config;
75
76
    protected OrganizationImageCacheManager $imageCacheManager;
77
78
    protected ValidatorPluginManager $validator;
79
80
    protected RepositoryService $repositories;
81
82
    protected EventManager $appEvents;
83
84
    protected HelperPluginManager $viewHelper;
85
86
    /**
87
     * @var UploadHandler
88
     */
89
    private UploadHandler $uploadHandler;
90
91
    public function __construct(
92
        OrganizationImageCacheManager $imageCacheManager,
93
        ValidatorPluginManager $validator,
94
        RepositoryService $repositories,
95
        EventManager $appEvents,
96
        HelperPluginManager $viewHelper,
97
        UploadHandler $uploadHandler,
98
        array $config
99
    )
100
    {
101
        $this->imageCacheManager = $imageCacheManager;
102
        $this->validator = $validator;
103
        $this->repositories = $repositories;
104
        $this->appEvents = $appEvents;
105
        $this->viewHelper = $viewHelper;
106
        $this->config = $config;
107
        $this->uploadHandler = $uploadHandler;
108
    }
109
110
	/**
111
	 * @param ContainerInterface $container
112
	 *
113
	 * @return ApplyController
114
	 */
115
    static public function factory(ContainerInterface $container)
116
    {
117
        $config            = $container->get('Config');
118
        $imageCacheManager = $container->get('Organizations\ImageFileCache\Manager');
119
        $validator         = $container->get('ValidatorManager');
120
        $repositories      = $container->get('repositories');
121
        $appEvents         = $container->get('Applications/Events');
122
        $viewHelper        = $container->get('ViewHelperManager');
123
        $uploadHandler     = $container->get(UploadHandler::class);
124
125
        return new self(
126
            $imageCacheManager,
127
            $validator,
128
            $repositories,
129
            $appEvents,
130
            $viewHelper,
131
            $uploadHandler,
132
            $config
133
        );
134
    }
135
136
	public function attachDefaultListeners()
137
	{
138
		parent::attachDefaultListeners();
139
		$events = $this->getEventManager();
140
		$events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
141
		return $this;
142
	}
143
144
    public function preDispatch(MvcEvent $e)
145
    {
146
        /* @var $application \Applications\Entity\Application */
147
        if ($this->params()->fromQuery('do')) {
148
            $e->getRouteMatch()->setParam('action', 'do');
149
            return;
150
        }
151
152
        /* @var $request    Request */
153
        /* @var $repository \Applications\Repository\Application */
154
        /* @var $container  Apply */
155
        $request      = $this->getRequest();
156
        $services     = $e->getApplication()->getServiceManager();
157
        $repositories = $services->get('repositories');
158
        $repository   = $repositories->get('Applications/Application');
159
        $container    = $services->get('forms')->get('Applications/Apply');
160
161
        if ($request->isPost()) {
0 ignored issues
show
Bug introduced by
The method isPost() does not exist on Laminas\Stdlib\RequestInterface. It seems like you code against a sub-type of Laminas\Stdlib\RequestInterface such as Laminas\Http\Request. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

161
        if ($request->/** @scrutinizer ignore-call */ isPost()) {
Loading history...
162
            $appId = $this->params()->fromPost('applicationId');
163
            if (!$appId) {
164
                throw new RuntimeException('Missing application id.');
165
            }
166
            $routeMatch = $e->getRouteMatch();
167
168
            if ('recruiter-preview' == $appId) {
169
                $routeMatch->setParam('action', 'process-preview');
170
                return;
171
            }
172
173
            $application = $repository->find($appId);
174
            if (!$application) {
175
                throw new RuntimeException('Invalid application id.');
176
            }
177
178
            $action     = 'process';
179
180
            $routeMatch->setParam('action', $action);
181
        } else {
182
            $user  = $this->auth()->getUser();
183
            $appId = $this->params('applyId');
184
            if (!$appId) {
185
                throw new RuntimeException('Missing apply id');
186
            }
187
188
            /* @var Job $jobRepo */
189
            $jobRepo = $repositories->get('Jobs/Job');
190
            $job = $jobRepo->findOneByApplyId($appId);
0 ignored issues
show
Bug introduced by
It seems like $appId can also be of type Laminas\Mvc\Controller\Plugin\Params; however, parameter $appId of Jobs\Repository\Job::findOneByApplyId() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

190
            $job = $jobRepo->findOneByApplyId(/** @scrutinizer ignore-type */ $appId);
Loading history...
191
192
            if (!$job) {
193
                $e->getRouteMatch()->setParam('action', 'job-not-found');
194
                return;
195
            }
196
197
            switch ($job->getStatus()) {
198
                case \Jobs\Entity\Status::ACTIVE:
199
                    break;
200
                default:
201
                    $e->getRouteMatch()->setParam('action', 'job-not-found');
202
                    return;
203
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
204
            }
205
206
            if ($user === $job->getUser()) {
207
                $application = new \Applications\Entity\Application();
208
                $application->setContact(new Contact());
209
                $application->setJob($job);
210
                $application->setId('recruiter-preview');
211
            } else {
212
                $subscriberUri = $this->params()->fromQuery('subscriber');
213
                $application   = $repository->findDraft($user, $appId);
214
215
                if ($application) {
216
                    /* @var $form UserInfo */
217
                    $form = $container->getForm('contact.contact');
218
                    $form->setDisplayMode('summary');
219
220
                    if ($subscriberUri) {
221
                        $subscriber = $application->getSubscriber();
222
                        if (!$subscriber || $subscriber->uri != $subscriberUri) {
223
                            $subscriber = $repositories->get('Applications/Subscriber')->findbyUri($subscriberUri, /*create*/ true);
224
                            $application->setSubscriber($subscriber);
225
                            $subscriber->getname();
226
                        }
227
                    }
228
                } else {
229
                    if (!$job) {
0 ignored issues
show
introduced by
$job is of type object, thus it always evaluated to true.
Loading history...
230
                        $e->getRouteMatch()->setParam('action', 'job-not-found');
231
                        return;
232
                    }
233
                    if ($job->getUriApply()) {
234
                        return $this->redirect($job->getUriApply());
0 ignored issues
show
Unused Code introduced by
The call to Laminas\Mvc\Controller\A...tController::redirect() has too many arguments starting with $job->getUriApply(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

234
                        return $this->/** @scrutinizer ignore-call */ redirect($job->getUriApply());

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
235
                    }
236
237
                    /* @var $application \Applications\Entity\Application */
238
                    $application = $repository->create();
239
                    $application->setIsDraft(true)
240
                                ->setContact($user->getInfo())
241
                                ->setUser($user)
242
                                ->setJob($job);
243
244
                    if ($subscriberUri) {
245
                        $subscriber = $repositories->get('Applications/Subscriber')->findbyUri($subscriberUri, /*create*/ true);
246
                        $application->setSubscriber($subscriber);
247
                    }
248
249
                    $repositories->store($application);
250
                    /*
251
                     * If we had copy an user image, we need to refresh its data
252
                     * to populate the length property.
253
                     */
254
                    if ($image = $application->getContact()->getImage()) {
255
                        $repositories->refresh($image);
256
                    }
257
                }
258
            }
259
        }
260
261
        $container->setEntity($application);
262
        $this->configureContainer($container);
263
        $this->formContainer     = $container;
264
    }
265
266
    public function jobNotFoundAction()
267
    {
268
        $this->response->setStatusCode(410);
0 ignored issues
show
Bug introduced by
The method setStatusCode() does not exist on Laminas\Stdlib\ResponseInterface. It seems like you code against a sub-type of Laminas\Stdlib\ResponseInterface such as Laminas\Http\Response. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

268
        $this->response->/** @scrutinizer ignore-call */ 
269
                         setStatusCode(410);
Loading history...
269
        $model = new ViewModel(
270
            [ 'content' => /*@translate*/ 'Invalid apply id']
271
        );
272
        $model->setTemplate('applications/error/not-found');
273
        return $model;
274
    }
275
276
    public function indexAction()
277
    {
278
        /* @var Apply $form */
279
        $form        = $this->formContainer;
280
        $application = $form->getEntity(); /* @var \Applications\Entity\Application $application */
281
282
        $form->setParam('applicationId', $application->getId());
283
284
        $organizationImageCache = $this->imageCacheManager;
285
286
        $model = new ViewModel(
287
            [
288
            'form' => $form,
289
            'isApplicationValid' => $this->checkApplication($application),
290
            'application' => $application,
291
            'organizationImageCache' =>  $organizationImageCache
292
            ]
293
        );
294
        $model->setTemplate('applications/apply/index');
295
        return $model;
296
    }
297
298
    public function oneClickApplyAction()
299
    {
300
        /* @var \Applications\Entity\Application $application */
301
        $application = $this->formContainer->getEntity();
302
        $job = $application->getJob();
303
        $atsMode = $job->getAtsMode();
304
305
        // check for one click apply
306
        if (!($atsMode->isIntern() && $atsMode->getOneClickApply()))
307
        {
308
            // redirect to regular application
309
            return $this->redirect()
310
                ->toRoute('lang/apply', ['applyId' => $job->getApplyId()]);
311
        }
312
313
        $network = $this->params('network');
314
315
        $hybridAuth = $this->formContainer
316
            ->get('HybridAuthAdapter')
317
            ->getHybridAuth();
318
        /* @var $authProfile Hybrid_User_Profile */
319
        $authProfile = $hybridAuth->authenticate($network)
320
           ->getUserProfile();
321
322
        /* @var AbstractProfile $profile */
323
        $profile = $this->plugin('Auth/SocialProfiles')->fetch($network);
0 ignored issues
show
Bug introduced by
The method fetch() does not exist on Laminas\Stdlib\DispatchableInterface. It seems like you code against a sub-type of Laminas\Stdlib\DispatchableInterface such as Laminas\Mvc\Controller\AbstractController. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

323
        $profile = $this->plugin('Auth/SocialProfiles')->/** @scrutinizer ignore-call */ fetch($network);
Loading history...
324
325
        $contact = $application->getContact();
326
        $contact->setEmail($authProfile->emailVerified ?: $authProfile->email);
327
        $contact->setFirstName($authProfile->firstName);
328
        $contact->setLastName($authProfile->lastName);
329
        $contact->setBirthDay($authProfile->birthDay);
330
        $contact->setBirthMonth($authProfile->birthMonth);
331
        $contact->setBirthYear($authProfile->birthYear);
332
        $contact->setPostalCode($authProfile->zip);
333
        $contact->setCity($authProfile->city);
334
        $contact->setStreet($authProfile->address);
335
        $contact->setPhone($authProfile->phone);
336
        $contact->setGender($authProfile->gender);
337
338
        $profiles = $application->getProfiles();
339
        $profiles->add($profile);
340
341
        $cv = $application->getCv();
342
        $cv->setEmployments($profile->getEmployments());
343
        $cv->setEducations($profile->getEducations());
344
345
        if ($authProfile->photoURL)
346
        {
347
            $response = (new Client($authProfile->photoURL, ['sslverifypeer' => false]))->send();
348
            $file = new GridFSFile();
349
            $file->setBytes($response->getBody());
350
351
            $image = new Attachment();
352
            $image->setName($contact->getLastName().$contact->getFirstName());
353
            $image->setType($response->getHeaders()->get('Content-Type')->getFieldValue());
0 ignored issues
show
Bug introduced by
The method getFieldValue() does not exist on ArrayIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

353
            $image->setType($response->getHeaders()->get('Content-Type')->/** @scrutinizer ignore-call */ getFieldValue());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method setType() does not exist on Applications\Entity\Attachment. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

353
            $image->/** @scrutinizer ignore-call */ 
354
                    setType($response->getHeaders()->get('Content-Type')->getFieldValue());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
354
            $image->setFile($file);
0 ignored issues
show
Bug introduced by
The method setFile() does not exist on Applications\Entity\Attachment. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

354
            $image->/** @scrutinizer ignore-call */ 
355
                    setFile($file);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
355
            $image->setPermissions($application->getPermissions());
0 ignored issues
show
Bug introduced by
The method setPermissions() does not exist on Applications\Entity\Attachment. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

355
            $image->/** @scrutinizer ignore-call */ 
356
                    setPermissions($application->getPermissions());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
356
357
            $contact->setImage($image);
358
        }
359
360
        $urlOptions = [];
361
362
        if ($this->params('immediately'))
363
        {
364
            $application->getAttributes()->setAcceptedPrivacyPolicy(true);
365
            $urlOptions = [
366
                'query' => [
367
                    'do' => 'send'
368
                ]
369
            ];
370
        }
371
372
        return $this->redirect()
373
           ->toRoute('lang/apply', ['applyId' => $job->getApplyId()], $urlOptions);
374
    }
375
376
    public function processPreviewAction()
377
    {
378
        return new JsonModel(array('valid' => false, 'errors' => array()));
379
    }
380
381
    public function processAction()
382
    {
383
    	$params = $this->params();
384
        $formName  = $params->fromQuery('form');
385
        $form      = $this->formContainer->getForm($formName);
386
        $postData  = $form->getOption('use_post_array') ? $params->fromPost() : array();
387
        $uploadHandler = $this->uploadHandler;
388
389
	    //@TODO: [ZF3] option use_files_array is false by default
390
        //$filesData = $form->getOption('use_files_array') ? $params->fromFiles() : array();
391
392
        $form->setData(array_merge($postData,$_FILES));
393
        if('contact.image' === $formName){
394
            $application = $uploadHandler->handleImageUpload($postData['applicationId'], $_FILES['image']);
395
            $form->getParent()->setEntity($application->getContact());
396
            $content = $this->viewHelper->get('form')->__invoke($form);
397
            return new JsonModel([
398
                'valid' => true,
399
                'content' => $content,
400
                'isApplicationValid' => $this->checkApplication($application)
401
            ]);
402
        }elseif('attachments' === $formName){
403
            $attachment = $uploadHandler->handleAttachmentUpload($postData['applicationId'], $_FILES['attachments']);
404
            $basepath = $this->viewHelper->get('basepath');
405
            $content = $basepath($attachment->getUri());
406
            $application = $uploadHandler->findApplication($postData['applicationId']);
407
            return new JsonModel([
408
                'valid' => true,
409
                'content' => $content,
410
                'isApplicationValid' => $this->checkApplication($application)
411
            ]);
412
        } else{
413
            if (!$form->isValid()) {
414
                return new JsonModel(
415
                    array(
416
                        'valid' => false,
417
                        'errors' => $form->getMessages(),
418
                    )
419
                );
420
            }
421
            $application = $this->formContainer->getEntity();
422
            $this->repositories->store($application);
423
        }
424
425
        if ($form instanceof SummaryForm) {
426
            $form->setRenderMode(SummaryForm::RENDER_SUMMARY);
427
            $viewHelper = 'summaryForm';
428
        } else {
429
            $viewHelper = 'form';
430
        }
431
        $content = $this->viewHelper->get($viewHelper)->__invoke($form);
432
433
        return new JsonModel(
434
            array(
435
	            'valid' => $form->isValid(),
436
	            'content' => $content,
437
	            'isApplicationValid' => $this->checkApplication($application)
438
            )
439
        );
440
    }
441
442
    public function doAction()
443
    {
444
        $config       = $this->config;
445
        $repositories = $this->repositories;
446
        $repository   = $repositories->get('Applications/Application');
447
        $organizationImageCache = $this->imageCacheManager;
448
        /* @var Application $application*/
449
        $application  = $repository->findDraft(
0 ignored issues
show
Bug introduced by
The method findDraft() does not exist on Doctrine\Persistence\ObjectRepository. It seems like you code against a sub-type of Doctrine\Persistence\ObjectRepository such as Jobs\Repository\Job or Cv\Repository\Cv or Applications\Repository\Application or Organizations\Repository\Organization. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

449
        /** @scrutinizer ignore-call */ 
450
        $application  = $repository->findDraft(
Loading history...
450
            $this->auth()->getUser(),
451
            $this->params('applyId')
452
        );
453
454
        if (!$application) {
0 ignored issues
show
introduced by
$application is of type Applications\Entity\Application, thus it always evaluated to true.
Loading history...
455
            throw new Exception('No application draft found.');
456
        }
457
458
        if ('abort' == $this->params()->fromQuery('do')) {
459
            $repositories->remove($application);
460
            return $this->redirect()->toRoute('lang/apply', array('applyId' => $this->params('applyId')));
461
        }
462
463
        if (!$this->checkApplication($application)) {
464
            $this->notification()->error(/*@translate*/ 'There are missing required informations. Your application cannot be send.');
465
            return $this->redirect()->toRoute('lang/apply', array('applyId' => $this->params('applyId')));
466
        }
467
468
        if ('previewmail' == $this->params()->fromQuery('do')) {
469
            $this->mailer('Applications/CarbonCopy', [ 'application' => $application], true);
0 ignored issues
show
Unused Code introduced by
The call to Applications\Controller\ApplyController::mailer() has too many arguments starting with 'Applications/CarbonCopy'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

469
            $this->/** @scrutinizer ignore-call */ 
470
                   mailer('Applications/CarbonCopy', [ 'application' => $application], true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
470
            $this->notification()->success(/*@translate*/ 'Mail has been send');
471
            return new JsonModel();
472
        }
473
474
        if ('sendmail' == $this->params()->fromQuery('do')) {
475
            $jobEntity         = $application->getJob();
476
477
            $mailData = array(
478
                'application' => $application,
479
                'to'          => $jobEntity->getContactEmail()
480
            );
481
            if (array_key_exists('mails', $config) && array_key_exists('from', $config['mails']) && array_key_exists('email', $config['mails']['from'])) {
482
                $mailData['from'] = $config['mails']['from']['email'];
483
            }
484
            $this->mailer('Applications/CarbonCopy', $mailData, true);
485
            $repositories->remove($application);
486
            //$this->notification()->success(/*@translate*/ 'Application has been send.');
487
            $model = new ViewModel(
488
                array(
489
                'organizationImageCache' =>  $organizationImageCache,
490
                'success' => true,
491
                'job' => $jobEntity,
492
                )
493
            );
494
            $model->setTemplate('applications/apply/success');
495
            return $model;
496
        }
497
498
        $application->setIsDraft(false)
499
            ->setStatus(new Status())
500
            ->getPermissions()
501
            ->revoke($this->auth()->getUser(), PermissionsInterface::PERMISSION_CHANGE)
502
            ->inherit($application->getJob()->getPermissions());
503
504
        $repositories->store($application);
505
506
        $events   = $this->appEvents;
507
        $events->trigger(ApplicationEvent::EVENT_APPLICATION_POST_CREATE, $this, [ 'application' => $application ]);
508
509
        $model = new ViewModel(
510
            array(
511
            'success' => true,
512
            'application' => $application,
513
            'organizationImageCache' =>  $organizationImageCache,
514
            )
515
        );
516
        $model->setTemplate('applications/apply/index');
517
518
        return $model;
519
    }
520
521
    protected function checkApplication($application)
522
    {
523
        return $this->validator->get('Applications/Application')
524
                    ->isValid($application);
525
    }
526
527
    /**
528
     * Configures the apply form container.
529
     *
530
     * Currently only disables elements.
531
     *
532
     * @param Container $container
533
     */
534
    protected function configureContainer(Container $container)
535
    {
536
        /* @var $application Application */
537
        $application = $container->getEntity();
538
        $job         = $application->getJob();
539
540
        /** @var $settings Settings */
541
        $settings = ($user = $job->getUser()) ? $user->getSettings('Applications') : null;
542
        $formSettings = $settings ? $settings->getApplyFormSettings() : null;
0 ignored issues
show
introduced by
$settings is of type Applications\Entity\Settings, thus it always evaluated to true.
Loading history...
543
544
        if ($formSettings && $formSettings->isActive()) {
545
            $container->disableElements($formSettings->getDisableElements());
546
            return;
547
        }
548
549
        $config = $this->config;
550
        $config = isset($config['form_elements_config']['Applications/Apply']['disable_elements'])
551
                ? $config['form_elements_config']['Applications/Apply']['disable_elements']
552
                : null;
553
        if ($config) {
554
            $container->disableElements($config);
555
        }
556
    }
557
}
558