GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Renderer::setRulePluginManager()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Renderer for the jquery.validate plugin
4
 *
5
 * @category  StrokerForm
6
 * @package   StrokerForm\Renderer
7
 * @copyright 2012 Bram Gerritsen
8
 * @version   SVN: $Id$
9
 */
10
11
namespace StrokerForm\Renderer\JqueryValidate;
12
13
use StrokerForm\Renderer\AbstractValidateRenderer;
14
use StrokerForm\Renderer\JqueryValidate\Rule\RuleInterface;
15
use StrokerForm\Renderer\JqueryValidate\Rule\RulePluginManager;
16
use Zend\Form\Element\Email;
17
use Zend\Form\ElementInterface;
18
use Zend\Form\FormInterface;
19
use Zend\Json\Json;
20
use Zend\Validator\EmailAddress;
21
use Zend\Validator\Regex;
22
use Zend\Validator\ValidatorInterface;
23
use Zend\View\Renderer\PhpRenderer as View;
24
25
class Renderer extends AbstractValidateRenderer
26
{
27
    /**
28
     * @var array
29
     */
30
    protected $skipValidators = [
31
        'Explode',
32
        'Upload'
33
    ];
34
35
    /**
36
     * @var array
37
     */
38
    protected $rules = [];
39
40
    /**
41
     * @var array
42
     */
43
    protected $messages = [];
44
45
    /**
46
     * @var RulePluginManager
47
     */
48
    protected $rulePluginManager;
49
50
    /**
51
     * @param RulePluginManager $rulePluginManager
52
     */
53
    public function setRulePluginManager(RulePluginManager $rulePluginManager)
54
    {
55
        $this->rulePluginManager = $rulePluginManager;
56
    }
57
58
    /**
59
     * @return RulePluginManager
60
     */
61
    public function getRulePluginManager()
62
    {
63
        return $this->rulePluginManager;
64
    }
65
66
    /**
67
     * Executed before the ZF2 view helper renders the element
68
     *
69
     * @param string                          $formAlias
70
     * @param \Zend\View\Renderer\PhpRenderer $view
71
     * @param \Zend\Form\FormInterface        $form
72
     * @param array                           $options
73
     *
74
     * @return FormInterface
75
     */
76
    public function preRenderForm($formAlias, View $view, FormInterface $form = null, array $options = [])
77
    {
78
        $form = parent::preRenderForm($formAlias, $view, $form, $options);
79
80
        /** @var $options Options */
81
        $options = $this->getOptions();
82
83
        $inlineScript = $view->plugin('inlineScript');
84
        $inlineScript->appendScript($this->buildInlineJavascript($form, $options));
85
86
        if ($options->getIncludeAssets()) {
87
            $assetBaseUri = $this->getHttpRouter()->assemble([], ['name' => 'strokerform-asset']);
88
            $inlineScript->appendFile($assetBaseUri . '/jquery_validate/js/jquery.validate.js');
89
            $inlineScript->appendFile($assetBaseUri . '/jquery_validate/js/custom_rules.js');
90
            if ($options->isUseTwitterBootstrap() === true) {
91
                $inlineScript->appendFile($assetBaseUri . '/jquery_validate/js/jquery.validate.bootstrap.js');
92
            }
93
        }
94
95
        $this->reset();
96
        return $form;
97
    }
98
99
    /**
100
     * @param  \Zend\Form\FormInterface $form
101
     * @param Options                   $options
102
     *
103
     * @return string
104
     */
105
    protected function buildInlineJavascript(FormInterface $form, Options $options)
106
    {
107
        $validateOptions = [];
108
        foreach ($options->getValidateOptions() as $key => $value) {
109
            $value = (is_string($value)) ? $value : var_export($value, true);
110
            $validateOptions[] = '"' . $key . '": ' . $value;
111
        }
112
113
        return sprintf(
114
            $options->getInitializeTrigger(),
115
            sprintf(
116
                '$(\'form[name="%s"]\').each(function() { $(this).validate({%s"rules":%s,"messages":%s}); });',
117
                $form->getName(),
118
                count($validateOptions) > 0 ? implode(',', $validateOptions) . ',' : '',
119
                Json::encode($this->rules),
120
                Json::encode($this->messages)
121
            )
122
        );
123
    }
124
125
    /**
126
     * @param string                             $formAlias
127
     * @param \Zend\Form\ElementInterface        $element
128
     * @param \Zend\Validator\ValidatorInterface $validator
129
     *
130
     * @return mixed|void
131
     */
132
    protected function addValidationAttributesForElement($formAlias, ElementInterface $element, ValidatorInterface $validator = null)
133
    {
134
        if (in_array($this->getValidatorClassName($validator), $this->skipValidators)) {
135
            return;
136
        }
137
        if ($element instanceof Email && $validator instanceof Regex) {
138
            $validator = new EmailAddress();
139
        }
140
141
        $rule = $this->getRule($validator);
142
        $rules = [];
143
        if ($rule !== null) {
144
            $rules = $rule->getRules($validator, $element);
145
            $messages = $rule->getMessages($validator);
146
        } elseif (!$this->getOptions()->isDisableAjaxFallback()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class StrokerForm\Renderer\Options as the method isDisableAjaxFallback() does only exist in the following sub-classes of StrokerForm\Renderer\Options: StrokerForm\Renderer\JqueryValidate\Options. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
147
            //fallback ajax
148
            $ajaxUri = $this->getHttpRouter()->assemble(['form' => $formAlias], ['name' => 'strokerform-ajax-validate']);
149
            $rules = [
150
                'remote' => [
151
                    'url'  => $ajaxUri,
152
                    'type' => 'POST'
153
                ]
154
            ];
155
            $messages = [];
156
        }
157
158
        if (count($rules) > 0) {
159
            $elementName = $this->getElementName($element);
160
            $this->addRules($elementName, $rules);
161
            $this->addMessages($elementName, $messages);
0 ignored issues
show
Bug introduced by
The variable $messages does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
162
        }
163
    }
164
165
    /**
166
     * @param  \Zend\Validator\ValidatorInterface $validator
167
     *
168
     * @return null|RuleInterface
169
     */
170
    public function getRule(ValidatorInterface $validator = null)
171
    {
172
        foreach ($this->getRulePluginManager()->getRegisteredServices() as $rules) {
173
            foreach ($rules as $rule) {
174
                $ruleInstance = $this->getRulePluginManager()->get($rule);
175
                if ($ruleInstance->canHandle($validator)) {
176
                    return $ruleInstance;
177
                }
178
            }
179
        }
180
181
        return;
182
    }
183
184
    /**
185
     * @param string $elementName
186
     * @param array  $rules
187
     */
188
    protected function addRules($elementName, array $rules = [])
189
    {
190
        if (!isset($this->rules[$elementName])) {
191
            $this->rules[$elementName] = [];
192
        }
193
        $this->rules[$elementName] = array_merge($this->rules[$elementName], $rules);
194
    }
195
196
    /**
197
     * @param string $elementName
198
     * @param array  $messages
199
     */
200
    protected function addMessages($elementName, array $messages = [])
201
    {
202
        if (!isset($this->messages[$elementName])) {
203
            $this->messages[$elementName] = [];
204
        }
205
        $this->messages[$elementName] = array_merge($this->messages[$elementName], $messages);
206
    }
207
208
    /**
209
     * Resets previously set rules and messages, if you have multiple forms on one request
210
     */
211
    protected function reset()
212
    {
213
        $this->rules = [];
214
        $this->messages = [];
215
    }
216
}
217