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.
Completed
Push — develop ( 8f8143...6b03f2 )
by Bram
03:02
created

Renderer::addValidationAttributesForElement()   C

Complexity

Conditions 7
Paths 13

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 21
nc 13
nop 3
dl 0
loc 32
rs 6.7272
c 0
b 0
f 0
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\I18n\Translator\TranslatorAwareInterface;
20
use Zend\Json\Json;
21
use Zend\Validator\EmailAddress;
22
use Zend\Validator\Regex;
23
use Zend\Validator\ValidatorInterface;
24
use Zend\View\Renderer\PhpRenderer as View;
25
26
class Renderer extends AbstractValidateRenderer
27
{
28
    /**
29
     * @var array
30
     */
31
    protected $skipValidators = [
32
        'Explode',
33
        'Upload'
34
    ];
35
36
    /**
37
     * @var array
38
     */
39
    protected $rules = [];
40
41
    /**
42
     * @var array
43
     */
44
    protected $messages = [];
45
46
    /**
47
     * @var RulePluginManager
48
     */
49
    protected $rulePluginManager;
50
51
    /**
52
     * @param RulePluginManager $rulePluginManager
53
     */
54
    public function setRulePluginManager(RulePluginManager $rulePluginManager)
55
    {
56
        $this->rulePluginManager = $rulePluginManager;
57
    }
58
59
    /**
60
     * @return RulePluginManager
61
     */
62
    public function getRulePluginManager()
63
    {
64
        return $this->rulePluginManager;
65
    }
66
67
    /**
68
     * Executed before the ZF2 view helper renders the element
69
     *
70
     * @param string                          $formAlias
71
     * @param \Zend\View\Renderer\PhpRenderer $view
72
     * @param \Zend\Form\FormInterface        $form
73
     * @param array                           $options
74
     *
75
     * @return FormInterface
76
     */
77
    public function preRenderForm($formAlias, View $view, FormInterface $form = null, array $options = [])
78
    {
79
        $form = parent::preRenderForm($formAlias, $view, $form, $options);
80
81
        /** @var $options Options */
82
        $options = $this->getOptions();
83
84
        $inlineScript = $view->plugin('inlineScript');
85
        $inlineScript->appendScript($this->buildInlineJavascript($form, $options));
86
87
        if ($options->getIncludeAssets()) {
88
            $assetBaseUri = $this->getHttpRouter()->assemble([], ['name' => 'strokerform-asset']);
89
            $inlineScript->appendFile($assetBaseUri . '/jquery_validate/js/jquery.validate.js');
90
            $inlineScript->appendFile($assetBaseUri . '/jquery_validate/js/custom_rules.js');
91
            if ($options->isUseTwitterBootstrap() === true) {
92
                $inlineScript->appendFile($assetBaseUri . '/jquery_validate/js/jquery.validate.bootstrap.js');
93
            }
94
        }
95
96
        $this->reset();
97
        return $form;
98
    }
99
100
    /**
101
     * @param  \Zend\Form\FormInterface $form
102
     * @param Options                   $options
103
     *
104
     * @return string
105
     */
106
    protected function buildInlineJavascript(FormInterface $form, Options $options)
107
    {
108
        $validateOptions = [];
109
        foreach ($options->getValidateOptions() as $key => $value) {
110
            $value = (is_string($value)) ? $value : var_export($value, true);
111
            $validateOptions[] = '"' . $key . '": ' . $value;
112
        }
113
114
        return sprintf(
115
            $options->getInitializeTrigger(),
116
            sprintf(
117
                '$(\'form[name="%s"]\').each(function() { $(this).validate({%s"rules":%s,"messages":%s}); });',
118
                $form->getName(),
119
                count($validateOptions) > 0 ? implode(',', $validateOptions) . ',' : '',
120
                Json::encode($this->rules),
121
                Json::encode($this->messages)
122
            )
123
        );
124
    }
125
126
    /**
127
     * @param string                             $formAlias
128
     * @param \Zend\Form\ElementInterface        $element
129
     * @param \Zend\Validator\ValidatorInterface $validator
130
     *
131
     * @return mixed|void
132
     */
133
    protected function addValidationAttributesForElement($formAlias, ElementInterface $element, ValidatorInterface $validator = null)
134
    {
135
        if (in_array($this->getValidatorClassName($validator), $this->skipValidators)) {
136
            return;
137
        }
138
        if ($element instanceof Email && $validator instanceof Regex) {
139
            $validator = new EmailAddress();
140
        }
141
142
        $rule = $this->getRule($validator);
143
        $rules = [];
144
        if ($rule !== null) {
145
            $rules = $rule->getRules($validator, $element);
146
            $messages = $rule->getMessages($validator);
147
        } 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...
148
            //fallback ajax
149
            $ajaxUri = $this->getHttpRouter()->assemble(['form' => $formAlias], ['name' => 'strokerform-ajax-validate']);
150
            $rules = [
151
                'remote' => [
152
                    'url'  => $ajaxUri,
153
                    'type' => 'POST'
154
                ]
155
            ];
156
            $messages = [];
157
        }
158
159
        if (count($rules) > 0) {
160
            $elementName = $this->getElementName($element);
161
            $this->addRules($elementName, $rules);
162
            $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...
163
        }
164
    }
165
166
    /**
167
     * @param  \Zend\Validator\ValidatorInterface $validator
168
     *
169
     * @return null|RuleInterface
170
     */
171
    public function getRule(ValidatorInterface $validator = null)
172
    {
173
        foreach ($this->getRulePluginManager()->getRegisteredServices() as $rules) {
174
            foreach ($rules as $rule) {
175
                $ruleInstance = $this->getRulePluginManager()->get($rule);
176
                if ($ruleInstance->canHandle($validator)) {
177
                    return $ruleInstance;
178
                }
179
            }
180
        }
181
182
        return null;
183
    }
184
185
    /**
186
     * @param string $elementName
187
     * @param array  $rules
188
     */
189
    protected function addRules($elementName, array $rules = [])
190
    {
191
        if (!isset($this->rules[$elementName])) {
192
            $this->rules[$elementName] = [];
193
        }
194
        $this->rules[$elementName] = array_merge($this->rules[$elementName], $rules);
195
    }
196
197
    /**
198
     * @param string $elementName
199
     * @param array  $messages
200
     */
201
    protected function addMessages($elementName, array $messages = [])
202
    {
203
        if (!isset($this->messages[$elementName])) {
204
            $this->messages[$elementName] = [];
205
        }
206
        $this->messages[$elementName] = array_merge($this->messages[$elementName], $messages);
207
    }
208
209
    /**
210
     * Resets previously set rules and messages, if you have multiple forms on one request
211
     */
212
    protected function reset()
213
    {
214
        $this->rules = [];
215
        $this->messages = [];
216
    }
217
}
218