Completed
Push — develop ( 65d553...40f996 )
by
unknown
12:00
created

JobboardController::indexAction()   C

Complexity

Conditions 10
Paths 20

Size

Total Lines 60
Code Lines 38

Duplication

Lines 13
Ratio 21.67 %

Importance

Changes 8
Bugs 0 Features 2
Metric Value
c 8
b 0
f 2
dl 13
loc 60
rs 6.5333
cc 10
eloc 38
nc 20
nop 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013-2015 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** ActionController of Jobs */
11
namespace Jobs\Controller;
12
13
use Jobs\Form\ListFilter;
14
use Zend\Mvc\Controller\AbstractActionController;
15
use Zend\Session\Container as Session;
16
use Jobs\Repository;
17
use Zend\View\Model\ViewModel;
18
19
/**
20
 * @method \Auth\Controller\Plugin\Auth auth()
21
 * @method \Core\Controller\Plugin\CreatePaginatorService paginatorService()
22
 *
23
 * Controller for jobboard actions
24
 */
25
class JobboardController extends AbstractActionController
26
{
27
    /**
28
     * @var Repository\Job $jobRepository
29
     */
30
    private $jobRepository;
31
32
    /**
33
     * Formular for searching job postings
34
     *
35
     * @var ListFilter $searchForm
36
     */
37
    private $searchForm;
38
39
    /**
40
     * Construct the jobboard controller
41
     *
42
     * @param Repository\Job $jobRepository
43
     * @param ListFilter $searchForm
44
     */
45
    public function __construct(Repository\Job $jobRepository, ListFilter $searchForm)
46
    {
47
        $this->jobRepository = $jobRepository;
48
        $this->searchForm = $searchForm;
49
    }
50
    /**
51
     * attaches further Listeners for generating / processing the output
52
     * @return $this
53
     */
54 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...
55
    {
56
        parent::attachDefaultListeners();
57
        $serviceLocator = $this->getServiceLocator();
58
        $defaultServices = $serviceLocator->get('DefaultListeners');
59
        $events          = $this->getEventManager();
60
        $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...
61
        return $this;
62
    }
63
64
    /**
65
     * List jobs
66
     *
67
     * @return ViewModel
68
     */
69
    public function indexAction()
70
    {
71
        /* @var \Zend\Http\Request $request */
72
        $request          = $this->getRequest();
73
        $params           = $request->getQuery();
74
        $jsonFormat       = 'json' == $request->getQuery()->get('format');
75
        $event            = $this->getEvent();
76
        $routeMatch       = $event->getRouteMatch();
77
        $matchedRouteName = $routeMatch->getMatchedRouteName();
78
        $url              = $this->url()->fromRoute($matchedRouteName, array(), array('force_canonical' => true));
79
80 View Code Duplication
        if (!$jsonFormat && !$request->isXmlHttpRequest()) {
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...
81
            $session = new Session('Jobs\Index');
82
            $sessionKey = $this->auth()->isLoggedIn() ? 'userParams' : 'guestParams';
83
            $sessionParams = $session[$sessionKey];
84
            if ($sessionParams) {
85
                foreach ($sessionParams as $key => $value) {
86
                    $params->set($key, $params->get($key, $value));
87
                }
88
            }
89
            $session[$sessionKey] = $params->toArray();
90
91
            $this->searchForm->bind($params);
92
        }
93
94
        $params = $params->get('params', []);
95
96
        if (isset($params['l']['data']) &&
97
            isset($params['l']['name']) &&
98
            !empty($params['l']['name'])) {
99
            /* @var \Geo\Form\GeoText $geoText */
100
            $geoText = $this->searchForm->get('params')->get('l');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Form\ElementInterface as the method get() does only exist in the following implementations of said interface: Applications\Form\Apply, Applications\Form\Attributes, Applications\Form\Base, Applications\Form\BaseFieldset, Applications\Form\CarbonCopyFieldset, Applications\Form\CommentForm, Applications\Form\ContactContainer, Applications\Form\Facts, Applications\Form\FactsFieldset, Applications\Form\FilterApplication, Applications\Form\Mail, Applications\Form\SettingsFieldset, Auth\Form\ForgotPassword, Auth\Form\Group, Auth\Form\GroupFieldset, Auth\Form\GroupUsersCollection, Auth\Form\Login, Auth\Form\Register, Auth\Form\SocialProfiles, Auth\Form\SocialProfilesFieldset, Auth\Form\UserBase, Auth\Form\UserBaseFieldset, Auth\Form\UserInfo, Auth\Form\UserInfoContainer, Auth\Form\UserInfoFieldset, Auth\Form\UserPassword, Auth\Form\UserPasswordFieldset, Auth\Form\UserProfileContainer, Core\Form\BaseForm, Core\Form\ButtonsFieldset, Core\Form\Container, Core\Form\DefaultButtonsFieldset, Core\Form\Form, Core\Form\FormSubmitButtonsFieldset, Core\Form\ListFilterButtonsFieldset, Core\Form\LocalizationSettingsFieldset, Core\Form\PermissionsCollection, Core\Form\PermissionsFieldset, Core\Form\RatingFieldset, Core\Form\SummaryForm, Core\Form\SummaryFormButtonsFieldset, Core\Form\ViewPartialProviderAbstract, Cv\Form\Cv, Cv\Form\CvFieldset, Cv\Form\EducationFieldset, Cv\Form\EmploymentFieldset, Cv\Form\LanguageFieldset, Cv\Form\NativeLanguageFieldset, Cv\Form\SkillFieldset, Install\Form\Installation, Jobs\Form\AtsMode, Jobs\Form\AtsModeFieldset, Jobs\Form\Base, Jobs\Form\BaseFieldset, Jobs\Form\CompanyName, Jobs\Form\CompanyNameFieldset, Jobs\Form\Import, Jobs\Form\ImportFieldset, Jobs\Form\Job, Jobs\Form\JobDescription, Jobs\Form\JobDescriptionBenefits, Jobs\Form\JobDescriptionDescription, Jobs\Form\JobDescriptionFieldset, Jobs\Form\JobDescriptionQualifications, Jobs\Form\JobDescriptionRequirements, Jobs\Form\JobDescriptionTemplate, Jobs\Form\JobDescriptionTitle, Jobs\Form\ListFilter, Jobs\Form\ListFilterAdminFieldset, Jobs\Form\ListFilterBaseFieldset, Jobs\Form\ListFilterLocationFieldset, Jobs\Form\ListFilterPersonalFieldset, Jobs\Form\Multipost, Jobs\Form\MultipostButtonFieldset, Jobs\Form\MultipostFieldset, Jobs\Form\Preview, Jobs\Form\PreviewFieldset, Jobs\Form\TemplateLabelBenefits, Jobs\Form\TemplateLabelQualifications, Jobs\Form\TemplateLabelRequirements, Organizations\Form\EmployeeFieldset, Organizations\Form\Employees, Organizations\Form\EmployeesFieldset, Organizations\Form\Organizations, Organizations\Form\OrganizationsContactFieldset, Organizations\Form\OrganizationsContactForm, Organizations\Form\Organ...ionsDescriptionFieldset, Organizations\Form\OrganizationsDescriptionForm, Organizations\Form\OrganizationsFieldset, Organizations\Form\OrganizationsNameFieldset, Organizations\Form\OrganizationsNameForm, Settings\Form\AbstractSettingsForm, Settings\Form\DisableEle...bleFormSettingsFieldset, Settings\Form\FormAbstract, Settings\Form\Settings, Settings\Form\SettingsFieldset, Zend\Form\Element\Collection, Zend\Form\Fieldset, Zend\Form\Form, Zend\Form\InputFilterProviderFieldset.

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...
101
102
            $geoText->setValue($params['l']);
103
            $params['location'] = $geoText->getValue('entity');
104
        }
105
106
        if (!isset($params['sort'])) {
107
            $params['sort']='-date';
108
        }
109
110
        $this->searchForm->setAttribute('action', $url);
111
112
        $params['by'] = "guest";
113
114
        $paginator = $this->paginatorService('Jobs/Board', $params);
0 ignored issues
show
Unused Code introduced by
The call to JobboardController::paginatorService() has too many arguments starting with 'Jobs/Board'.

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...
115
116
        $options = $this->searchForm->getOptions();
117
        $options['showButtons'] = false;
118
        $this->searchForm->setOptions($options);
119
        
120
        $return = array(
121
            'by' => $params['by'],
122
            'jobs' => $paginator,
123
            'filterForm' => $this->searchForm
124
        );
125
        $model = new ViewModel($return);
126
127
        return $model;
128
    }
129
}