Completed
Pull Request — develop (#236)
by ANTHONIUS
07:34
created

IndexController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 4
rs 10
c 1
b 1
f 0
cc 1
eloc 2
nc 1
nop 1
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
/** ActionController of Core */
11
namespace Cv\Controller;
12
13
use Cv\Form\SearchForm;
14
use Zend\Mvc\Controller\AbstractActionController;
15
use Zend\View\Model\ViewModel;
16
use Zend\Session\Container as Session;
17
18
/**
19
 * Main Action Controller for the application.
20
 * Responsible for displaying the home site.
21
 *
22
 */
23
class IndexController extends AbstractActionController
24
{
25
    /**
26
     * @var SearchForm
27
     */
28
    protected $searchForm;
29
30
    public function __construct(SearchForm $searchForm)
31
    {
32
        $this->searchForm = $searchForm;
33
    }
34
35
    /**
36
     * attaches further Listeners for generating / processing the output
37
     * @return $this
38
     */
39 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...
40
    {
41
        parent::attachDefaultListeners();
42
        $serviceLocator  = $this->serviceLocator;
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
        return $this;
47
    }
48
49
    /**
50
     * Home site
51
     *
52
     */
53
    public function indexAction()
54
    {
55
        /* @var \Zend\Http\Request $request */
56
        $request = $this->getRequest();
57
        $params = $request->getQuery();
58
        $jsonFormat = 'json' == $request->getQuery()->get('format');
59
        $event = $this->getEvent();
60
        $routeMatch = $event->getRouteMatch();
61
        $matchedRouteName = $routeMatch->getMatchedRouteName();
62
        $url = $this->url()->fromRoute($matchedRouteName, array(), array('force_canonical' => true));
63
64
65 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...
66
            $session = new Session('Cv\Index');
67
            $sessionKey = $this->auth()->isLoggedIn() ? 'userParams' : 'guestParams';
0 ignored issues
show
Documentation Bug introduced by
The method auth does not exist on object<Cv\Controller\IndexController>? 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...
68
            $sessionParams = $session[$sessionKey];
69
            if ($sessionParams) {
70
                foreach ($sessionParams as $key => $value) {
71
                    $params->set($key, $params->get($key, $value));
72
                }
73
            }
74
            $session[$sessionKey] = $params->toArray();
75
76
            $this->searchForm->bind($params);
77
        }
78
79
        $params = $params->get('params', []);
80
81 View Code Duplication
        if (isset($params['l']['data']) &&
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...
82
            isset($params['l']['name']) &&
83
            !empty($params['l']['name'])
84
        ) {
85
            /* @var \Geo\Form\GeoText $geoText */
86
            $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, Auth\Form\UserStatus, Auth\Form\UserStatusContainer, Auth\Form\UserStatusFieldset, Core\Form\BaseForm, Core\Form\ButtonsFieldset, Core\Form\CollectionContainer, 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\TextSearchForm, Core\Form\TextSearchFormButtonsFieldset, Core\Form\TextSearchFormFieldset, Core\Form\ViewPartialProviderAbstract, Core\Form\WizardContainer, Cv\Form\CvContainer, Cv\Form\EducationFieldset, Cv\Form\EducationForm, Cv\Form\EmploymentFieldset, Cv\Form\EmploymentForm, Cv\Form\LanguageSkillFieldset, Cv\Form\LanguageSkillForm, Cv\Form\NativeLanguageFieldset, Cv\Form\NativeLanguageForm, Cv\Form\PreferredJobFieldset, Cv\Form\PreferredJobForm, Cv\Form\SearchForm, Cv\Form\SearchFormFieldset, Cv\Form\SkillFieldset, Cv\Form\SkillForm, Install\Form\Installation, Jobs\Form\AdminJobEdit, Jobs\Form\AdminSearchForm, Jobs\Form\AdminSearchFormElementsFieldset, 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\ListFilterAdmin, Jobs\Form\ListFilterAdminFieldset, Jobs\Form\ListFilterBaseFieldset, Jobs\Form\ListFilterLocation, Jobs\Form\ListFilterLocationFieldset, Jobs\Form\ListFilterPersonal, 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, Orders\Form\InvoiceAddress, Orders\Form\InvoiceAddressFieldset, Orders\Form\InvoiceAddressSettingsFieldset, 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, Organizations\Form\WorkflowSettings, Organizations\Form\WorkflowSettingsFieldset, 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...
87
88
            $geoText->setValue($params['l']);
89
            $params['location'] = $geoText->getValue('entity');
90
        }
91
92
93
        $this->searchForm->setAttribute('action', $url);
94
        $paginator = $this->paginator('Cv/Paginator', $params);
0 ignored issues
show
Documentation Bug introduced by
The method paginator does not exist on object<Cv\Controller\IndexController>? 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...
95
96
        $options = $this->searchForm->getOptions();
97
        $options['showButtons'] = false;
98
        $this->searchForm->setOptions($options);
99
100
        $return = array(
101
            'resumes' => $paginator,
102
            'filterForm' => $this->searchForm
103
        );
104
        $model = new ViewModel($return);
105
106
        return $model;
107
    }
108
}
109