SummaryForm   B
last analyzed

Complexity

Total Complexity 48

Size/Duplication

Total Lines 285
Duplicated Lines 0 %

Test Coverage

Coverage 47.29%

Importance

Changes 0
Metric Value
wmc 48
eloc 152
dl 0
loc 285
ccs 61
cts 129
cp 0.4729
rs 8.5599
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 15 4
A renderForm() 0 25 4
B renderSummary() 0 40 8
B render() 0 58 5
D renderSummaryElement() 0 100 27

How to fix   Complexity   

Complex Class

Complex classes like SummaryForm often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SummaryForm, and based on these observations, apply Extract Interface, too.

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
/**  */
11
namespace Core\Form\View\Helper;
12
13
use Core\Form\SummaryFormInterface;
14
use Laminas\Form\Element\Hidden;
15
use Laminas\Form\FormInterface;
16
use Laminas\Form\View\Helper\AbstractHelper;
17
use Laminas\Form\ElementInterface;
18
use Laminas\Form\FieldsetInterface;
19
use Core\Form\ViewPartialProviderInterface;
20
use Core\Form\DescriptionAwareFormInterface;
21
use Core\Form\EmptySummaryAwareInterface;
22
23
/**
24
 * Helper to render a summary form container.
25
 *
26
 * @author Mathias Gelhausen <[email protected]>
27
 */
28
class SummaryForm extends AbstractHelper
29
{
30
    
31
    /**
32
     * Invoke as function.
33
     *
34
     * @param null|SummaryFormInterface $form
35
     * @param string $layout
36
     * @param array $parameter
37
     * @return \Core\Form\View\Helper\SummaryForm|string
38
     */
39 1
    public function __invoke(SummaryFormInterface $form = null, $layout = Form::LAYOUT_HORIZONTAL, $parameter = array())
40
    {
41 1
        if (null === $form) {
42
            return $this;
43
        }
44
        
45 1
        $mode = $form->getRenderMode();
46 1
        if (SummaryFormInterface::RENDER_FORM == $mode) {
47
            return $this->renderForm($form, $layout, $parameter);
48
        }
49 1
        if (SummaryFormInterface::RENDER_SUMMARY == $mode) {
50
            return $this->renderSummary($form);
51
        }
52
        
53 1
        return $this->render($form, $layout, $parameter);
54
    }
55
    
56
    /**
57
     * Renders a summary form container.
58
     *
59
     * @param SummaryFormInterface $form
60
     * @param string $layout
61
     * @param array $parameter
62
     * @return string
63
     */
64 1
    public function render(SummaryFormInterface $form, $layout = Form::LAYOUT_HORIZONTAL, $parameter = array())
65
    {
66 1
        $renderer = $this->getView();
67 1
        $renderer->headscript()->appendFile($renderer->basepath('modules/Core/js/jquery.summary-form.js'));
0 ignored issues
show
Bug introduced by
The method basepath() does not exist on Laminas\View\Renderer\RendererInterface. It seems like you code against a sub-type of Laminas\View\Renderer\RendererInterface such as Laminas\View\Renderer\PhpRenderer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

67
        $renderer->headscript()->appendFile($renderer->/** @scrutinizer ignore-call */ basepath('modules/Core/js/jquery.summary-form.js'));
Loading history...
Bug introduced by
The method headscript() does not exist on Laminas\View\Renderer\RendererInterface. It seems like you code against a sub-type of Laminas\View\Renderer\RendererInterface such as Laminas\View\Renderer\PhpRenderer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

67
        $renderer->/** @scrutinizer ignore-call */ 
68
                   headscript()->appendFile($renderer->basepath('modules/Core/js/jquery.summary-form.js'));
Loading history...
68
        
69 1
        $label = $form->getLabel();
70 1
        $labelContent = $label ? '<div class="sf-headline"><h3>' . $this->getView()->translate($label) . '</h3></div>' : '';
0 ignored issues
show
Bug introduced by
The method translate() does not exist on Laminas\View\Renderer\RendererInterface. It seems like you code against a sub-type of Laminas\View\Renderer\RendererInterface such as Laminas\View\Renderer\PhpRenderer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

70
        $labelContent = $label ? '<div class="sf-headline"><h3>' . $this->getView()->/** @scrutinizer ignore-call */ translate($label) . '</h3></div>' : '';
Loading history...
71 1
        $formContent  = $this->renderForm($form, $layout, $parameter);
72 1
        $summaryContent = $this->renderSummary($form);
73
        
74 1
        $formContent = sprintf(
75 1
            '<div class="sf-form"><div class="panel panel-info"><div class="panel-body">%s</div></div></div>
76
                 <div class="sf-summary">%s</div>
77
                ',
78
            $formContent,
79
            $summaryContent
80
        );
81
        
82 1
        if ($form instanceof DescriptionAwareFormInterface && $form->isDescriptionsEnabled()) {
83
            $this->getView()->headscript()->appendFile(
84
                $this->getView()->basepath('modules/Core/js/forms.descriptions.js')
85
            );
86
        
87
            if ($desc = $form->getOption('description', '')) {
0 ignored issues
show
Unused Code introduced by
The call to Laminas\Form\ElementInterface::getOption() has too many arguments starting with ''. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

87
            if ($desc = $form->/** @scrutinizer ignore-call */ getOption('description', '')) {

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. Please note the @ignore annotation hint above.

Loading history...
88
                $translator = $this->getTranslator();
89
                $textDomain = $this->getTranslatorTextDomain();
90
        
91
                $desc = $translator->translate($desc, $textDomain);
92
            }
93
        
94
            $formContent = sprintf(
95
                '<div class="daf-form-container row">
96
                        <div class="daf-form col-md-8">%s</div>
97
                        <div class="daf-desc col-md-4">
98
                            <div class="daf-desc-content alert alert-info">%s</div>
99
                        </div>
100
                    </div>',
101
                $formContent,
102
                $desc
103
            );
104
        }
105
        
106
        $markup = '<div id="sf-%s" class="sf-container" data-display-mode="%s">'
107
                . '%s'
108
                . '%s'
109 1
                . '</div>';
110
        
111 1
        $id = str_replace('.', '-', $form->getAttribute('name'));
112 1
        $content = sprintf(
113 1
            $markup,
114
            $id,
115 1
            $form->getDisplayMode(),
116
            $labelContent,
117
            $formContent
118
        );
119
        
120
        
121 1
        return $content;
122
    }
123
124
    /**
125
     * Only renders the form representation of a summary form.
126
     *
127
     * @param SummaryFormInterface $form
128
     * @param string $layout
129
     * @param array $parameter
130
     * @return string
131
     */
132 1
    public function renderForm(SummaryFormInterface $form, $layout = Form::LAYOUT_HORIZONTAL, $parameter = array())
133
    {
134
        /* @var $form SummaryFormInterface|\Core\Form\SummaryForm */
135 1
        $renderer     = $this->getView();           /* @var $renderer \Laminas\View\Renderer\PhpRenderer */
136
        $formHelper   = $renderer->plugin('form');  /* @var $formHelper \Core\Form\View\Helper\Form */
137 1
        $fieldset     = $form->getBaseFieldset();
0 ignored issues
show
Bug introduced by
The method getBaseFieldset() does not exist on Core\Form\SummaryFormInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Core\Form\SummaryFormInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

137
        /** @scrutinizer ignore-call */ 
138
        $fieldset     = $form->getBaseFieldset();
Loading history...
138 1
        $resetPartial = false;
139
140 1
        if ($fieldset instanceof ViewPartialProviderInterface) {
141 1
            $origPartial = $fieldset->getViewPartial();
142 1
            $partial     = "$origPartial.form";
143 1
            if ($renderer->resolver($partial)) {
144 1
                $fieldset->setViewPartial($partial);
145 1
                $resetPartial = true;
146
            }
147
        }
148
149 1
        $markup = $formHelper->renderBare($form, $layout, $parameter);
150
151 1
        if ($resetPartial) {
152
            /** @noinspection PhpUndefinedVariableInspection */
153 1
            $fieldset->setViewPartial($origPartial);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $origPartial does not seem to be defined for all execution paths leading up to this point.
Loading history...
Bug introduced by
The method setViewPartial() does not exist on Laminas\Form\FieldsetInterface. It seems like you code against a sub-type of Laminas\Form\FieldsetInterface such as Auth\Form\UserStatusFieldset or Core\Form\ButtonsFieldset or Jobs\Form\SalaryFieldset or Jobs\Form\AtsModeFieldset or Jobs\Form\PreviewFieldset or Organizations\Form\EmployeesFieldset or Organizations\Form\EmployeeFieldset or Organizations\Form\WorkflowSettingsFieldset or Auth\Form\SocialProfilesFieldset or Core\Form\PermissionsFieldset or Core\Form\Tree\AddItemFieldset or Cv\Form\EmploymentFieldset or Cv\Form\PreferredJobFieldset or Core\Form\Tree\ManagementFieldset or Cv\Form\EducationFieldset or Jobs\Form\CompanyNameFieldset or Auth\Form\UserInfoFieldset or Jobs\Form\CustomerNoteFieldset or Jobs\Form\ListFilter or Jobs\Form\Preview or Auth\Form\GroupUsersCollection or Core\Form\PermissionsCollection or Jobs\Form\ListFilter or Jobs\Form\Preview. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
            $fieldset->/** @scrutinizer ignore-call */ 
154
                       setViewPartial($origPartial);
Loading history...
154
        }
155
156 1
        return $markup;
157
    }
158
    
159
    /**
160
     * Only renders the summary representation of a summary form
161
     *
162
     * @param SummaryFormInterface $form
163
     * @return string
164
     */
165 1
    public function renderSummary(SummaryFormInterface $form)
166
    {
167 1
        $form->prepare();
0 ignored issues
show
Bug introduced by
The method prepare() does not exist on Core\Form\SummaryFormInterface. Did you maybe mean prepareElement()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

167
        $form->/** @scrutinizer ignore-call */ 
168
               prepare();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
168 1
        $baseFieldset = $form->getBaseFieldset();
169 1
        if (!isset($baseFieldset)) {
170
            throw new \InvalidArgumentException('For the Form ' . get_class($form) . ' there is no Basefieldset');
171
        }
172
173 1
        $dataAttributesMarkup = '';
174
        
175 1
        foreach ($form->getAttributes() as $dataKey => $dataValue) {
176 1
            if (preg_match('/^data-/', $dataKey)) {
177
                $dataAttributesMarkup .= sprintf(' %s="%s"', $dataKey, $dataValue);
178
            }
179
        }
180
        
181 1
        $markup = '<div class="panel panel-default" style="min-height: 100px;"' . $dataAttributesMarkup . '>
182
                    <div class="panel-body"><div class="sf-controls">%s</div>%s</div></div>';
183
184 1
        $view = $this->getView();
185 1
        $buttonMarkup = false === $form->getOption('editable')
186
                      ? ''
187
                      : '<button type="button" class="btn btn-default btn-xs sf-edit">'
188
                        . '<span class="yk-icon yk-icon-edit"></span> '
189 1
                        . $view->translate('Edit')
190 1
                        . '</button>';
191
        
192 1
        if (($controlButtons = $form->getOption('control_buttons')) !== null) {
193
            $buttonMarkup .= PHP_EOL . implode(PHP_EOL, array_map(function (array $buttonSpec) use ($view) {
194
                return '<button type="button" class="btn btn-default btn-xs' . (isset($buttonSpec['class']) ? ' ' . $buttonSpec['class'] : '') . '">'
195
                    . (isset($buttonSpec['icon']) ? '<span class="yk-icon yk-icon-' . $buttonSpec['icon'] . '"></span> ' : '')
196
                    . $view->translate($buttonSpec['label'])
197
                    . '</button>';
198
            }, $controlButtons));
199
        }
200
201 1
        $elementMarkup = $this->renderSummaryElement($baseFieldset);
202
203
204 1
        return sprintf($markup, $buttonMarkup, $elementMarkup);
205
    }
206
    
207
    /**
208
     * Helper function to recurse into form elements when rendering summary.
209
     *
210
     * @param ElementInterface $element
211
     * @return string
212
     */
213 1
    public function renderSummaryElement(ElementInterface $element)
214
    {
215 1
        if ($element instanceof Hidden || false === $element->getOption('render_summary')) {
216
            return '';
217
        }
218
219 1
        if ($element instanceof EmptySummaryAwareInterface && $element->isSummaryEmpty()) {
220
            /* @var $element EmptySummaryAwareInterface|ElementInterface */
221
            $emptySummaryNotice = $this->getTranslator()->translate(
222
                $element->getEmptySummaryNotice(),
0 ignored issues
show
Bug introduced by
The method getEmptySummaryNotice() does not exist on Laminas\Form\ElementInterface. It seems like you code against a sub-type of Laminas\Form\ElementInterface such as Applications\Form\BaseFieldset or Applications\Form\FactsFieldset or Cv\Form\NativeLanguageFieldset or Cv\Form\PreferredJobFieldset or Auth\Form\UserInfoFieldset or Applications\Form\BaseFieldset or Applications\Form\FactsFieldset or Cv\Form\NativeLanguageFieldset or Cv\Form\PreferredJobFieldset or Auth\Form\UserInfoFieldset. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

222
                $element->/** @scrutinizer ignore-call */ 
223
                          getEmptySummaryNotice(),
Loading history...
223
                $this->getTranslatorTextDomain()
224
            );
225
226
            $markup = sprintf(
227
                '<div id="%s-empty-alert" class="empty-summary-notice alert alert-info"><p>%s</p></div>',
228
                $element->getAttribute('id'),
0 ignored issues
show
Bug introduced by
The method getAttribute() does not exist on Core\Form\EmptySummaryAwareInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Core\Form\EmptySummaryAwareInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

228
                $element->/** @scrutinizer ignore-call */ 
229
                          getAttribute('id'),
Loading history...
229
                $emptySummaryNotice
230
            );
231
            return $markup;
232
        }
233
234 1
        if ($element instanceof ViewPartialProviderInterface) {
235 1
            $renderer    = $this->getView();                 /* @var $renderer \Laminas\View\Renderer\PhpRenderer */
236 1
            $origPartial = $element->getViewPartial();
237 1
            $partial     = "$origPartial.view";
238
            $partialParams  = array(
239 1
                'element' => $element
240
            );
241 1
            if (!$renderer->resolver($partial)) {
242
                $partial = $origPartial;
243
                $partialParams['renderSummary'] = true;
244
            }
245
    
246 1
            return $renderer->partial($partial, $partialParams);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $renderer->partia...artial, $partialParams) also could return the type Laminas\View\Helper\Partial which is incompatible with the documented return type string.
Loading history...
247
        }
248
    
249
        $label  = $this->getTranslator()->translate($element->getLabel());
250
        $markup = '';
251
        
252
        if ($element instanceof FieldsetInterface) {
253
            if (!$element instanceof FormInterface && $label) {
254
                $markup .= '<h4>' . $label . '</h4>';
255
            }
256
            foreach ($element as $el) {
257
                $markup .= $this->renderSummaryElement($el);
258
            }
259
            return $markup;
260
        }
261
    
262
        $elementValue = $element instanceof \Laminas\Form\Element\Textarea
263
                      ? nl2br($element->getValue())
264
                      : $element->getValue();
265
266
        if ('' != $elementValue && $element instanceof \Core\Form\Element\Select) {
267
            if ($summaryValue = $element->getOption('summary_value')) {
268
                $elementValue = is_callable($summaryValue) ? $summaryValue() : $summaryValue;
269
            } else {
270
                $options = $element->getValueOptions();
271
                $translator = $this->getTranslator();
272
                if (true == $element->getAttribute('multiple')) {
273
                    $multiOptions = [];
274
                    foreach ($elementValue as $optionKey) {
275
                        if (isset($options[$optionKey])) {
276
                            $multiOptions[] = $translator->translate($options[$optionKey]);
277
                            continue;
278
                        }
279
280
                        foreach ($options as $optKey => $optVal) {
281
                            if (!is_array($optVal) || !array_key_exists($optionKey, $optVal['options'])) {
282
                                continue;
283
                            }
284
285
                            $optGroupLabel = isset($optVal['label']) ? $translator->translate($optVal['label']) : $optKey;
286
                            $multiOptions[] = $optGroupLabel . ' | ' . $translator->translate($optVal['options'][$optionKey]);
287
                        }
288
                    }
289
290
                    $elementValue = '<ul><li>' . join('</li><li>', $multiOptions) . '</li></ul>';
291
                } else {
292
                    $elementValue = $translator->translate($options[$elementValue]);
293
                }
294
            }
295
        }
296
297
        if ('' != $elementValue && $element instanceof \Laminas\Form\Element\File) {
298
            return '';
299
        }
300
                      
301
        $markup .= '<div class="row">';
302
        $col = 12;
303
        if ($label) {
304
            $markup .= '<div class="col-md-3 yk-label"><label>' . $label . '</label></div>';
305
            $col = 9;
306
        }
307
        if(is_array($elementValue)){
308
            $elementValue = implode(",", $elementValue);
309
        }
310
        $markup .= '<div class="col-md-' . $col . '">' . $elementValue . '</div>'
311
            . '</div>';
312
        return $markup;
313
    }
314
}
315