Completed
Pull Request — develop (#280)
by
unknown
11:07
created

ManageController::forwardAction()   B

Complexity

Conditions 3
Paths 6

Size

Total Lines 41
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 41
rs 8.8571
cc 3
eloc 28
nc 6
nop 0
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** Applications controller */
11
namespace Applications\Controller;
12
13
use Applications\Listener\Events\ApplicationEvent;
14
use Zend\Mvc\Controller\AbstractActionController;
15
use Zend\View\Model\ViewModel;
16
use Zend\View\Model\JsonModel;
17
use Applications\Entity\StatusInterface as Status;
18
use Applications\Entity\Application;
19
20
/**
21
 * @method \Core\Controller\Plugin\Notification notification()
22
 * @method \Core\Controller\Plugin\Mailer mailer()
23
 * @method \Acl\Controller\Plugin\Acl acl()
24
 * @method \Auth\Controller\Plugin\Auth auth()
25
 *
26
 * Handles managing actions on applications
27
 */
28
class ManageController extends AbstractActionController
29
{
30
    /**
31
     * attaches further Listeners for generating / processing the output
32
     *
33
     * @return $this
34
     */
35
    public function attachDefaultListeners()
36
    {
37
        parent::attachDefaultListeners();
38
        $serviceLocator  = $this->serviceLocator;
39
        $defaultServices = $serviceLocator->get('DefaultListeners');
40
        $events          = $this->getEventManager();
41
        $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...
42
        return $this;
43
    }
44
45
    /**
46
     * (non-PHPdoc)
47
     * @see \Zend\Mvc\Controller\AbstractActionController::onDispatch()
48
     */
49
    public function onDispatch(\Zend\Mvc\MvcEvent $e)
50
    {
51
        $routeMatch = $e->getRouteMatch();
52
        $action     = $this->params()->fromQuery('action');
53
        
54
        if ($routeMatch && $action) {
55
            $routeMatch->setParam('action', $action);
56
        }
57
58
        return parent::onDispatch($e);
59
    }
60
    
61
    /**
62
     * List applications
63
     */
64
    public function indexAction()
65
    {
66
        $services              = $this->serviceLocator;
67
        /* @var \Jobs\Repository\Job $jobRepository */
68
        $jobRepository         = $services->get('repositories')->get('Jobs/Job');
69
        /* @var \Applications\Repository\Application $applicationRepository */
70
        $applicationRepository = $services->get('repositories')->get('Applications/Application');
71
        $services_form         = $services->get('forms');
0 ignored issues
show
Coding Style introduced by
$services_form 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...
72
        /* @var \Applications\Form\FilterApplication $form */
73
        $form                  = $services_form->get('Applications/Filter');
0 ignored issues
show
Coding Style introduced by
$services_form 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...
74
        $params                = $this->getRequest()->getQuery();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method getQuery() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

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...
75
        /* @var \Zend\Form\Element\Select $statusElement */
76
        $statusElement         = $form->get('status');
77
78
        $states                = $applicationRepository->getStates()->toArray();
79
        $states                = array_merge(array(/*@translate*/ 'all'), $states);
80
        
81
        $statesForSelections = array();
82
        foreach ($states as $state) {
83
            $statesForSelections[$state] = $state;
84
        }
85
        $statusElement->setValueOptions($statesForSelections);
86
        
87
        $job = $params->job ? $jobRepository->find($params->job)  : null;
88
        $paginator = $this->paginator('Applications');
0 ignored issues
show
Documentation Bug introduced by
The method paginator does not exist on object<Applications\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...
89
90
        if ($job) {
91
            $params['job_title'] = '[' . $job->getApplyId() . '] ' . $job->getTitle();
92
        }
93
94
        $form->bind($params);
95
                
96
        return array(
97
            'form' => $form,
98
            'applications' => $paginator,
99
            'byJobs' => 'jobs' == $params->get('by', 'me'),
100
            'sort' => $params->get('sort', 'none'),
101
            'search' => $params->get('search', ''),
102
            'job' => $job,
103
            'applicationStates' => $states,
104
            'applicationState' => $params->get('status', '')
105
        );
106
    }
107
108
    /**
109
     * Detail view of an application
110
     *
111
     * @return array|JsonModel|ViewModel
112
     */
113
    public function detailAction()
114
    {
115
        if ('refresh-rating' == $this->params()->fromQuery('do')) {
116
            return $this->refreshRatingAction();
117
        }
118
        
119
        $nav = $this->serviceLocator->get('Core/Navigation');
120
        $page = $nav->findByRoute('lang/applications');
121
        $page->setActive();
122
123
        /* @var \Applications\Repository\Application$repository */
124
        $repository = $this->serviceLocator->get('repositories')->get('Applications/Application');
125
        /* @var Application $application */
126
        $application = $repository->find($this->params('id'));
127
        
128
        if (!$application) {
129
            $this->response->setStatusCode(410);
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...
130
            $model = new ViewModel(
131
                array(
132
                'content' => /*@translate*/ 'Invalid apply id'
133
                )
134
            );
135
            $model->setTemplate('applications/error/not-found');
136
            return $model;
137
        }
138
        
139
        $this->acl($application, 'read');
0 ignored issues
show
Unused Code introduced by
The call to ManageController::acl() has too many arguments starting with $application.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
140
        
141
        $applicationIsUnread = false;
142
        if ($application->isUnreadBy($this->auth('id')) && $application->getStatus()) {
0 ignored issues
show
Unused Code introduced by
The call to ManageController::auth() has too many arguments starting with 'id'.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Documentation introduced by
$this->auth('id') is of type object<Auth\Controller\Plugin\Auth>, but the function expects a object<Auth\Entity\UserInterface>|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...
143
            $application->addReadBy($this->auth('id'));
0 ignored issues
show
Unused Code introduced by
The call to ManageController::auth() has too many arguments starting with 'id'.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Documentation introduced by
$this->auth('id') is of type object<Auth\Controller\Plugin\Auth>, but the function expects a object<Auth\Entity\UserInterface>|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...
144
            $applicationIsUnread = true;
145
            $application->changeStatus(
146
                $application->getStatus(),
147
                sprintf(/*@translate*/ 'Application was read by %s',
148
                                       $this->auth()->getUser()->getInfo()->getDisplayName()));
149
        }
150
151
152
        
153
        $format=$this->params()->fromQuery('format');
154
155
        if ($application->isDraft()) {
156
            $list = false;
157
        } else {
158
            $list = $this->paginationParams('Applications\Index', $repository);
0 ignored issues
show
Bug introduced by
The method paginationParams() does not exist on Applications\Controller\ManageController. Did you maybe mean params()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
159
            $list->setCurrent($application->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...
160
        }
161
162
        $return = array(
163
            'application'=> $application,
164
            'list' => $list,
165
            'isUnread' => $applicationIsUnread,
166
            'format' => 'html'
167
        );
168
        switch ($format) {
169
            case 'json':
170
                /*@deprecated - must be refactored */
171
                        $viewModel = new JsonModel();
172
                        $viewModel->setVariables(
173
                            /*array(
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
174
                            'application' => */$this->serviceLocator
175
                                              ->get('builders')
176
                                              ->get('JsonApplication')
177
                                              ->unbuild($application)
178
                        );
179
                        $viewModel->setVariable('isUnread', $applicationIsUnread);
180
                        $return = $viewModel;
181
                break;
182
            case 'pdf':
183
                $pdf = $this->serviceLocator->get('Core/html2pdf');
0 ignored issues
show
Unused Code introduced by
$pdf 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...
184
                $return['format'] = $format;
185
                break;
186
            default:
187
                $contentCollector = $this->getPluginManager()->get('Core/ContentCollector');
188
                $contentCollector->setTemplate('applications/manage/details/action-buttons');
0 ignored issues
show
Bug introduced by
The method setTemplate() does not seem to exist on object<Zend\Stdlib\DispatchableInterface>.

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...
189
                $actionButtons = $contentCollector->trigger('application.detail.actionbuttons', $application);
0 ignored issues
show
Bug introduced by
The method trigger() does not seem to exist on object<Zend\Stdlib\DispatchableInterface>.

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...
190
                
191
                $return = new ViewModel($return);
192
                $return->addChild($actionButtons, 'externActionButtons');
193
                
194
                $allowSubsequentAttachmentUpload = $this->serviceLocator->get('Applications/Options')
195
                    ->getAllowSubsequentAttachmentUpload();
196
                
197
                if ($allowSubsequentAttachmentUpload)
198
                {
199
                    $attachmentsForm = $this->serviceLocator->get('forms')
200
                        ->get('Applications/Attachments');
201
                    $attachmentsForm->bind($application->getAttachments());
202
                    
203
                    /* @var $request \Zend\Http\PhpEnvironment\Request */
204
                    $request = $this->getRequest();
205
                    
206
                    if ($request->isPost() && $attachmentsForm->get('return')->getValue() === $request->getPost('return')) {
207
                        $data = array_merge(
208
                            $attachmentsForm->getOption('use_post_array') ? $request->getPost()->toArray() : [],
209
                            $attachmentsForm->getOption('use_files_array') ? $request->getFiles()->toArray() : []
210
                        );
211
                        $attachmentsForm->setData($data);
212
                        
213
                        if (!$attachmentsForm->isValid()) {
214
                            return new JsonModel([
215
                                'valid' => false,
216
                                'errors' => $attachmentsForm->getMessages()
217
                            ]);
218
                        }
219
                        
220
                        $content = $attachmentsForm->getHydrator()
221
                            ->getLastUploadedFile()
222
                            ->getUri();
223
                        
224
                        return new JsonModel([
225
                            'valid' => $attachmentsForm->isValid(),
226
                            'content' => $content
227
                        ]);
228
                    }
229
                    
230
                    $return->setVariable('attachmentsForm', $attachmentsForm);
231
                }
232
                
233
                break;
234
        }
235
        
236
        return $return;
237
    }
238
    
239
    /**
240
     * Refreshes the rating of an application
241
     *
242
     * @throws \DomainException
243
     * @return \Zend\View\Model\ViewModel
244
     */
245
    public function refreshRatingAction()
246
    {
247
        $model = new ViewModel();
248
        $model->setTemplate('applications/manage/_rating');
249
        
250
        $application = $this->serviceLocator->get('repositories')->get('Applications/Application')
251
                        ->find($this->params('id', 0));
252
        
253
        if (!$application) {
254
            throw new \DomainException('Invalid application id.');
255
        }
256
        
257
        $model->setVariable('application', $application);
258
        return $model;
259
    }
260
    
261
    /**
262
     * Attaches a social profile to an application
263
     * @throws \InvalidArgumentException
264
     *
265
     * @return array
266
     */
267
    public function socialProfileAction()
268
    {
269
        if ($spId = $this->params()->fromQuery('spId')) {
0 ignored issues
show
Unused Code introduced by
$spId 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...
270
            $repositories = $this->serviceLocator->get('repositories');
271
            $repo = $repositories->get('Applications/Application');
272
            $profile = $repo->findProfile($this->params()->fromQuery('spId'));
273
            if (!$profile) {
274
                throw new \InvalidArgumentException('Could not find profile.');
275
            }
276
        } elseif ($this->getRequest()->isPost()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method isPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

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...
277
                   && ($network = $this->params()->fromQuery('network'))
278
                   && ($data    = $this->params()->fromPost('data'))
279
        ) {
280
            $profileClass = '\\Auth\\Entity\\SocialProfiles\\' . $network;
281
            $profile      = new $profileClass();
282
            $profile->setData(\Zend\Json\Json::decode($data, \Zend\Json\Json::TYPE_ARRAY));
283
        } else {
284
            throw new \RuntimeException(
285
                'Missing arguments. Either provide "spId" as Get or "network" and "data" as Post.'
286
            );
287
        }
288
        
289
        return array(
290
            'profile' => $profile
291
        );
292
    }
293
294
    /**
295
     * Changes the status of an application
296
     *
297
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be \Zend\Stdlib\ResponseInterface|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
298
     */
299
    public function statusAction()
300
    {
301
        $applicationId = $this->params('id');
302
        /* @var \Applications\Repository\Application $repository */
303
        $repository    = $this->serviceLocator->get('repositories')->get('Applications/Application');
304
        /* @var Application $application */
305
        $application   = $repository->find($applicationId);
306
307
        /* @var Request $request */
308
        $request = $this->getRequest();
309
310
        if (!$application) {
311
            throw new \InvalidArgumentException('Could not find application.');
312
        }
313
        
314
        $this->acl($application, 'change');
0 ignored issues
show
Unused Code introduced by
The call to ManageController::acl() has too many arguments starting with $application.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
315
        
316
        $jsonFormat    = 'json' == $this->params()->fromQuery('format');
317
        $status        = $this->params('status', Status::CONFIRMED);
318
        $settings = $this->settings();
0 ignored issues
show
Documentation Bug introduced by
The method settings does not exist on object<Applications\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...
Unused Code introduced by
$settings 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...
319
        
320
        if (in_array($status, array(Status::INCOMING))) {
321
            $application->changeStatus($status);
322
            if ($request->isXmlHttpRequest()) {
323
                $response = $this->getResponse();
324
                $response->setContent('ok');
325
                return $response;
326
            }
327
            if ($jsonFormat) {
328
                return array(
329
                    'status' => 'success',
330
                );
331
            }
332
            return $this->redirect()->toRoute('lang/applications/detail', array(), true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a array.

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...
333
        }
334
335
        $events = $this->serviceLocator->get('Applications/Events');
336
337
        /* @var ApplicationEvent $event */
338
        $event = $events->getEvent(ApplicationEvent::EVENT_APPLICATION_STATUS_CHANGE,
339
                                   $this,
340
                                   [
341
                                       'application' => $application,
342
                                       'status' => $status,
343
                                       'user' => $this->auth()->getUser(),
344
                                   ]
345
        );
346
347
        $event->setIsPostRequest($request->isPost());
348
        $event->setPostData($request->getPost());
349
        $events->trigger($event);
350
351
        $params = $event->getFormData();
352
353
354
        if ($request->isPost()) {
355
356
            if ($jsonFormat) {
357
                return array(
358
                    'status' => 'success',
359
                );
360
            }
361
            $this->notification()->success($event->getNotification());
362
            return $this->redirect()->toRoute('lang/applications/detail', array(), true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a array.

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...
363
        }
364
365
        if ($jsonFormat) {
366
            return $params;
367
        }
368
369
        /* @var \Applications\Form\Mail $form */
370
        $form = $this->serviceLocator->get('FormElementManager')->get('Applications/Mail');
371
        $form->populateValues($params);
372
373
374
375
        $reciptient = $params['to'];
376
377
        return [
378
            'recipient' => $reciptient,
379
            'form' => $form
380
        ];
381
    }
382
    
383
    /**
384
     * Forwards an application via Email
385
     *
386
     * @throws \InvalidArgumentException
387
     * @return \Zend\View\Model\JsonModel
388
     */
389
    public function forwardAction()
390
    {
391
        $services     = $this->serviceLocator;
392
        $emailAddress = $this->params()->fromQuery('email');
393
        /* @var \Applications\Entity\Application $application */
394
        $application  = $services->get('repositories')->get('Applications/Application')
395
                                 ->find($this->params('id'));
396
        
397
        $this->acl($application, 'forward');
0 ignored issues
show
Unused Code introduced by
The call to ManageController::acl() has too many arguments starting with $application.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
398
        
399
        $translator   = $services->get('translator');
400
         
401
        if (!$emailAddress) {
402
            throw new \InvalidArgumentException('An email address must be supplied.');
403
        }
404
        
405
        $params = array(
406
            'ok' => true,
407
            'text' => sprintf($translator->translate('Forwarded application to %s'), $emailAddress)
408
        );
409
        
410
        try {
411
            $userName    = $this->auth('info')->displayName;
0 ignored issues
show
Bug introduced by
The property displayName does not seem to exist in Auth\Controller\Plugin\Auth.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Unused Code introduced by
The call to ManageController::auth() has too many arguments starting with 'info'.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
412
            $fromAddress = $application->getJob()->getContactEmail();
413
            $mailOptions = array(
414
                'application' => $application,
415
                'to'          => $emailAddress,
416
                'from'        => array($fromAddress => $userName)
417
            );
418
            $this->mailer('Applications/Forward', $mailOptions, true);
0 ignored issues
show
Unused Code introduced by
The call to ManageController::mailer() has too many arguments starting with 'Applications/Forward'.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
419
            $this->notification()->success($params['text']);
420
        } catch (\Exception $ex) {
421
            $params = array(
422
                'ok' => false,
423
                'text' => sprintf($translator->translate('Forward application to %s failed.'), $emailAddress)
424
            );
425
            $this->notification()->error($params['text']);
426
        }
427
        $application->changeStatus($application->getStatus(), $params['text']);
0 ignored issues
show
Bug introduced by
It seems like $application->getStatus() can be null; however, changeStatus() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
428
        return new JsonModel($params);
429
    }
430
431
    /**
432
     * Deletes an application
433
     *
434
     * @return array|\Zend\Http\Response
435
     */
436
    public function deleteAction()
437
    {
438
        $id          = $this->params('id');
439
        $services    = $this->serviceLocator;
440
        $repositories= $services->get('repositories');
441
        $repository  = $repositories->get('Applications/Application');
442
        $application = $repository->find($id);
443
        
444
        if (!$application) {
445
            throw new \DomainException('Application not found.');
446
        }
447
448
        $this->acl($application, 'delete');
0 ignored issues
show
Unused Code introduced by
The call to ManageController::acl() has too many arguments starting with $application.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
449
450
        $events   = $services->get('Applications/Events');
451
        $events->trigger(ApplicationEvent::EVENT_APPLICATION_PRE_DELETE, $this, [ 'application' => $application ]);
452
        
453
        $repositories->remove($application);
454
        
455
        if ('json' == $this->params()->fromQuery('format')) {
456
            return ['status' => 'success'];
457
        }
458
        
459
        return $this->redirect()->toRoute('lang/applications', array(), true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a array.

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...
460
    }
461
462
    /**
463
     * Move an application to talent pool
464
     *
465
     * @return \Zend\Http\Response
466
     * @since 0.26
467
     */
468
    public function moveAction()
469
    {
470
        $id = $this->params('id');
471
        $serviceManager = $this->serviceLocator;
472
        $repositories = $serviceManager->get('repositories');
473
        $application = $repositories->get('Applications/Application')->find($id);
474
        
475
        if (!$application) {
476
            throw new \DomainException('Application not found.');
477
        }
478
479
        $this->acl($application, 'move');
0 ignored issues
show
Unused Code introduced by
The call to ManageController::acl() has too many arguments starting with $application.

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

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

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
480
        
481
        $user = $this->auth()->getUser();
482
        $cv = $repositories->get('Cv/Cv')->createFromApplication($application, $user);
483
        
484
        $repositories->store($cv);
485
        $repositories->remove($application);
486
487
        $this->notification()->success(
488
            /*@translate*/ 'Application has been successfully moved to Talent Pool');
489
        
490
        return $this->redirect()->toRoute('lang/applications', array(), true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a array.

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...
491
    }
492
}
493