CatalogManagerFormRow::getInputErrorClass()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace SpeckCatalog\Form\View\Helper;
4
5
use Zend\Form\ElementInterface;
6
use Zend\Form\Exception;
7
use Zend\Form\View\Helper\AbstractHelper;
8
use Zend\Form\View\Helper\FormLabel;
9
use Zend\Form\View\Helper\FormElement;
10
use Zend\Form\View\Helper\FormElementErrors;
11
12
/**
13
 * @category   Zend
14
 * @package    Zend_Form
15
 * @subpackage View
16
 */
17
class CatalogManagerFormRow extends AbstractHelper
18
{
19
    const LABEL_APPEND  = 'append';
20
    const LABEL_PREPEND = 'prepend';
21
22
    /**
23
     * @var string
24
     */
25
    protected $labelPosition = self::LABEL_PREPEND;
26
27
    /**
28
     * @var bool
29
     */
30
    protected $renderErrors = true;
31
32
    /**
33
     * @var array
34
     */
35
    protected $labelAttributes;
36
37
    /**
38
     * @var string
39
     */
40
    protected $inputErrorClass = 'input-error';
41
42
    /**
43
     * @var FormLabel
44
     */
45
    protected $labelHelper;
46
47
    /**
48
     * @var FormElement
49
     */
50
    protected $elementHelper;
51
52
    /**
53
     * @var FormElementErrors
54
     */
55
    protected $elementErrorsHelper;
56
57
58
    /**
59
     * Utility form helper that renders a label (if it exists), an element and errors
60
     *
61
     * @param ElementInterface $element
62
     * @return string
63
     * @throws \Zend\Form\Exception\DomainException
64
     */
65
    public function render(ElementInterface $element)
66
    {
67
        $escapeHtmlHelper    = $this->getEscapeHtmlHelper();
68
        $labelHelper         = $this->getLabelHelper();
69
        $elementHelper       = $this->getElementHelper();
70
        $elementErrorsHelper = $this->getElementErrorsHelper();
71
72
        $label           = $element->getLabel();
73
        $inputErrorClass = $this->getInputErrorClass();
74
        $elementErrors   = $elementErrorsHelper->render($element);
75
76
        // Does this element have errors ?
77
        if (!empty($elementErrors) && !empty($inputErrorClass)) {
78
            $classAttributes = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
79
            $classAttributes = $classAttributes . $inputErrorClass;
80
81
            $element->setAttribute('class', $classAttributes);
82
        }
83
84
        $elementString = $elementHelper->render($element);
85
86
        if (isset($label) && '' !== $label) {
87
            // Translate the label
88
            if (null !== ($translator = $this->getTranslator())) {
89
                $label = $translator->translate(
90
                    $label,
91
                    $this->getTranslatorTextDomain()
92
                );
93
            }
94
95
            $label = $escapeHtmlHelper($label);
96
            $labelAttributes = $element->getLabelAttributes();
0 ignored issues
show
Bug introduced by
The method getLabelAttributes() does not exist on Zend\Form\ElementInterface. Did you maybe mean getLabel()?

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...
97
98
            if (empty($labelAttributes)) {
99
                $labelAttributes = $this->labelAttributes;
100
            }
101
102
            // Multicheckbox elements have to be handled differently as the HTML standard does not allow nested
103
            // labels. The semantic way is to group them inside a fieldset
104
            $type = $element->getAttribute('type');
105
            if ($type === 'multi_checkbox' || $type === 'radio') {
106
                $markup = sprintf(
107
                    '<fieldset><legend>%s</legend>%s</fieldset>',
108
                    $label,
109
                    $elementString
110
                );
111
            } else {
112
                if ($element->hasAttribute('id')) {
113
                    $labelOpen = $labelHelper($element);
114
                    $labelClose = '';
115
                    $label = '';
116
                } else {
117
                    $labelOpen  = $labelHelper->openTag($labelAttributes);
118
                    $labelClose = $labelHelper->closeTag();
119
                }
120
121
                if ($label !== '') {
122
                    $label = '<span>' . $label . '</span>';
123
                }
124
125
                switch ($this->labelPosition) {
126
                    case self::LABEL_PREPEND:
127
                        $markup = $labelOpen . $label . $elementString . $labelClose;
128
                        break;
129
                    case self::LABEL_APPEND:
130
                    default:
131
                        $markup = $labelOpen . $elementString . $label . $labelClose;
132
                        break;
133
                }
134
            }
135
136
            if ($this->renderErrors) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
137
                //$markup .= $elementErrors;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
138
            }
139
        } else {
140
            if ($this->renderErrors) {
141
                $markup = $elementString;  //. $elementErrors;
142
            } else {
143
                $markup = $elementString;
144
            }
145
        }
146
147
        return $markup;
148
    }
149
150
    /**
151
     * Invoke helper as functor
152
     *
153
     * Proxies to {@link render()}.
154
     *
155
     * @param null|ElementInterface $element
156
     * @param null|string           $labelPosition
157
     * @param bool                  $renderErrors
158
     * @return string|FormRow
159
     */
160
    public function __invoke(ElementInterface $element = null, $labelPosition = null, $renderErrors = true)
161
    {
162
        if (!$element) {
163
            return $this;
164
        }
165
166
        if ($labelPosition !== null) {
167
            $this->setLabelPosition($labelPosition);
168
        }
169
170
        $this->setRenderErrors($renderErrors);
171
172
        return $this->render($element);
173
    }
174
175
    /**
176
     * Set the label position
177
     *
178
     * @param $labelPosition
179
     * @return FormRow
180
     * @throws \Zend\Form\Exception\InvalidArgumentException
181
     */
182
    public function setLabelPosition($labelPosition)
183
    {
184
        $labelPosition = strtolower($labelPosition);
185
        if (!in_array($labelPosition, array(self::LABEL_APPEND, self::LABEL_PREPEND))) {
186
            throw new Exception\InvalidArgumentException(sprintf(
187
                '%s expects either %s::LABEL_APPEND or %s::LABEL_PREPEND; received "%s"',
188
                __METHOD__,
189
                __CLASS__,
190
                __CLASS__,
191
                (string) $labelPosition
192
            ));
193
        }
194
        $this->labelPosition = $labelPosition;
195
196
        return $this;
197
    }
198
199
    /**
200
     * Get the label position
201
     *
202
     * @return string
203
     */
204
    public function getLabelPosition()
205
    {
206
        return $this->labelPosition;
207
    }
208
209
    /**
210
     * Are the errors rendered by this helper ?
211
     *
212
     * @param  bool $renderErrors
213
     * @return FormRow
214
     */
215
    public function setRenderErrors($renderErrors)
216
    {
217
        $this->renderErrors = (bool) $renderErrors;
218
        return $this;
219
    }
220
221
    /**
222
     * @return bool
223
     */
224
    public function getRenderErrors()
225
    {
226
        return $this->renderErrors;
227
    }
228
229
    /**
230
     * Set the attributes for the row label
231
     *
232
     * @param  array $labelAttributes
233
     * @return FormRow
234
     */
235
    public function setLabelAttributes($labelAttributes)
236
    {
237
        $this->labelAttributes = $labelAttributes;
238
        return $this;
239
    }
240
241
    /**
242
     * Get the attributes for the row label
243
     *
244
     * @return array
245
     */
246
    public function getLabelAttributes()
247
    {
248
        return $this->labelAttributes;
249
    }
250
251
    /**
252
     * Set the class that is added to element that have errors
253
     *
254
     * @param  string $inputErrorClass
255
     * @return FormRow
256
     */
257
    public function setInputErrorClass($inputErrorClass)
258
    {
259
        $this->inputErrorClass = $inputErrorClass;
260
        return $this;
261
    }
262
263
    /**
264
     * Get the class that is added to element that have errors
265
     *
266
     * @return string
267
     */
268
    public function getInputErrorClass()
269
    {
270
        return $this->inputErrorClass;
271
    }
272
273
    /**
274
     * Retrieve the FormLabel helper
275
     *
276
     * @return FormLabel
277
     */
278
    protected function getLabelHelper()
279
    {
280
        if ($this->labelHelper) {
281
            return $this->labelHelper;
282
        }
283
284
        if (method_exists($this->view, 'plugin')) {
285
            $this->labelHelper = $this->view->plugin('form_label');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\View\Renderer\RendererInterface as the method plugin() does only exist in the following implementations of said interface: Zend\View\Renderer\PhpRenderer.

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...
286
        }
287
288
        if (!$this->labelHelper instanceof FormLabel) {
289
            $this->labelHelper = new FormLabel();
290
        }
291
292
        if ($this->hasTranslator()) {
293
            $this->labelHelper->setTranslator(
294
                $this->getTranslator(),
295
                $this->getTranslatorTextDomain()
296
            );
297
        }
298
299
        return $this->labelHelper;
300
    }
301
302
    /**
303
     * Retrieve the FormElement helper
304
     *
305
     * @return FormElement
306
     */
307
    protected function getElementHelper()
308
    {
309
        if ($this->elementHelper) {
310
            return $this->elementHelper;
311
        }
312
313
        if (method_exists($this->view, 'plugin')) {
314
            $this->elementHelper = $this->view->plugin('form_element');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\View\Renderer\RendererInterface as the method plugin() does only exist in the following implementations of said interface: Zend\View\Renderer\PhpRenderer.

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...
315
        }
316
317
        if (!$this->elementHelper instanceof FormElement) {
318
            $this->elementHelper = new FormElement();
319
        }
320
321
        return $this->elementHelper;
322
    }
323
324
    /**
325
     * Retrieve the FormElementErrors helper
326
     *
327
     * @return FormElementErrors
328
     */
329
    protected function getElementErrorsHelper()
330
    {
331
        if ($this->elementErrorsHelper) {
332
            return $this->elementErrorsHelper;
333
        }
334
335
        if (method_exists($this->view, 'plugin')) {
336
            $this->elementErrorsHelper = $this->view->plugin('form_element_errors');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\View\Renderer\RendererInterface as the method plugin() does only exist in the following implementations of said interface: Zend\View\Renderer\PhpRenderer.

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...
337
        }
338
339
        if (!$this->elementErrorsHelper instanceof FormElementErrors) {
340
            $this->elementErrorsHelper = new FormElementErrors();
341
        }
342
343
        return $this->elementErrorsHelper;
344
    }
345
}
346