ActiveForm::init()   F
last analyzed

Complexity

Conditions 12
Paths 576

Size

Total Lines 64
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 3.3125
c 0
b 0
f 0
cc 12
eloc 41
nc 576
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This file is part of the fangface/yii2-widgets package
4
 *
5
 * For the full copyright and license information, please view
6
 * the file LICENSE.md that was distributed with this source code.
7
 *
8
 * @package fangface/yii2-widgets
9
 * @author Fangface <[email protected]>
10
 * @copyright Copyright (c) 2014 Fangface <[email protected]>
11
 * @license https://github.com/fangface/yii2-widgets/blob/master/LICENSE.md MIT License
12
 *
13
 */
14
15
namespace fangface\forms;
16
17
use fangface\forms\ActiveField;
18
use yii\base\Model;
19
use yii\helpers\ArrayHelper;
20
use yii\helpers\Html;
21
use yii\helpers\Json;
22
use yii\widgets\ActiveFormAsset;
23
24
class ActiveForm extends \yii\widgets\ActiveForm
25
{
26
    // Buttons align
27
    const BUTTONS_ALIGN_LEFT = 'left';
28
29
    const BUTTONS_ALIGN_RIGHT = 'right';
30
    // Buttons position
31
    const BUTTONS_POSITION_TOP = 'top';
32
    const BUTTONS_POSITION_BOTTOM = 'bottom';
33
34
    // Form type
35
    const TYPE_HORIZONTAL = 'horizontal';
36
    const TYPE_VERTICAL = 'vertical';
37
    const TYPE_INLINE = 'inline';
38
39
    /**
40
     * @var bool Indicates whether form rows is separated.
41
     */
42
    public $separated = false;
43
44
    /**
45
     * @var bool Indicates whether form rows is stripped.
46
     */
47
    public $stripped = false;
48
49
    /**
50
     * @var bool Indicates whether form rows is bordered.
51
     */
52
    public $bordered = false;
53
54
    /**
55
     * @var string The default base class for the html form class attribute
56
     */
57
    public $defaultClass = 'general-form';
58
59
    /**
60
     * @var integer Set the full grid span
61
     */
62
    public $fullSpan = 12;
63
64
    /**
65
     * @var integer Set the label grid span
66
     */
67
    public $labelSpan = 3;
68
69
    /**
70
     * @var bool Indicates if form should be submitted using ajax
71
     */
72
    public $ajax = true;
73
74
    /**
75
     * @var string ActiveForm type.
76
     *      Valid values are 'horizontal', 'vertical', 'inline'
77
     */
78
    public $type = self::TYPE_VERTICAL;
79
80
    /* @var boolean should all fields within the form be treated as non editable */
81
    public $editLocked = false;
82
83
    /**
84
     *
85
     * @var array the [[ActiveForm]] buttons.
86
     *      Note that if are empty option 'items', then will not generated element is wrapped buttons.
87
     *      It is an array of the following structure:
88
     *      ```php
89
     *      [
90
     *      //optional, horizontal align
91
     *      'align' => ActiveForm::BUTTONS_POSITION_LEFT,
92
     *      //optional, vertical position
93
     *      'position' => ActiveForm::BUTTONS_POSITION_BOTTOM,
94
     *      //optional, array of buttons
95
     *      'items' => [
96
     *      Button::widget('label' => 'Save', 'options' => ['type' => 'submit']),
97
     *      Button::widget('label' => 'Back'),
98
     *      ],
99
     *      // optional, the HTML attributes (name-value pairs) for the form actions tag.
100
     *      'options' => ['class' => 'fluid']
101
     *      ]
102
     *      ```
103
     */
104
    public $buttons = [];
105
106
    /**
107
     *
108
     * @var array the default configuration used by [[field()]] when creating a new field object.
109
     */
110
    public $fieldConfig = [];
111
112
    /**
113
     *
114
     * @var bool indicates whether the tag 'form' is rendered.
115
     *      In case 'true' widget renders 'div' instead 'form'.
116
     */
117
    public $fake = false;
118
119
120
    /**
121
     * Initializes the widget.
122
     * This renders the form open tag.
123
     */
124
    public function init()
125
    {
126
        if (!isset($this->options['id'])) {
127
            $this->options['id'] = $this->getId();
128
        }
129
130
        if ($this->defaultClass) {
131
            Html::addCssClass($this->options, $this->defaultClass);
132
        }
133
134
        if ($this->ajax) {
135
            Html::addCssClass($this->options, 'ajaxform');
136
        }
137
138
        switch ($this->type) {
139
            case self::TYPE_HORIZONTAL:
140
                if ($this->stripped) {
141
                    Html::addCssClass($this->options, 'form-row-stripped');
142
                }
143
                if ($this->separated) {
144
                    Html::addCssClass($this->options, 'form-row-seperated');
145
                }
146
                if ($this->bordered) {
147
                    Html::addCssClass($this->options, 'form-bordered');
148
                }
149
                Html::addCssClass($this->options, 'form-horizontal');
150
                $this->fieldConfig = ArrayHelper::merge([
151
                    'labelOptions' => [
152
                        'class' => 'col-md-' . $this->labelSpan . ' control-label'
153
                    ],
154
                    'template' => "{label}\n" . Html::tag('div', "{input}\n{hint}\n{error}", [
155
                        'class' => 'col-md-' . ($this->fullSpan - $this->labelSpan)
156
                    ])
157
                ], $this->fieldConfig);
158
                if (false) { // wlchere - need to play with this once we know how the templates work out perhaps this needs to be an active field thing
159
                    // only useful because the hint and error blocks take up space even when no error or hint exists
160
                    $this->fieldConfig['template'] = str_replace("\n{error}", '', $this->fieldConfig['template']);
161
                }
162
                break;
163
            case self::TYPE_INLINE:
164
                Html::addCssClass($this->options, 'form-inline');
165
                $this->fieldConfig = ArrayHelper::merge([
166
                    'labelOptions' => [
167
                        'class' => 'sr-only'
168
                    ]
169
                ], $this->fieldConfig);
170
                break;
171
        }
172
173
        if (!isset($this->fieldConfig['class'])) {
174
            $this->fieldConfig['class'] = ActiveField::className();
175
        }
176
177
        if ($this->fake) {
178
            echo Html::beginTag('div', $this->options);
179
        } else {
180
            echo Html::beginForm($this->action, $this->method, $this->options);
181
        }
182
183
        echo $this->renderActions(self::BUTTONS_POSITION_TOP);
184
        echo Html::beginTag('div', [
185
            'class' => 'form-body'
186
        ]);
187
    }
188
189
190
    /**
191
     * Runs the widget.
192
     * This registers the necessary javascript code and renders the form close tag.
193
     */
194
    public function run()
195
    {
196
        echo Html::endTag('div');
197
        echo $this->renderActions(self::BUTTONS_POSITION_BOTTOM);
198
        if (true || ($this->enableClientScript && !empty($this->attributes))) {
0 ignored issues
show
Documentation introduced by
The property enableClientScript does not exist on object<fangface\forms\ActiveForm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
199
            $id = $this->options['id'];
200
            $options = Json::htmlEncode($this->getClientOptions());
0 ignored issues
show
Bug introduced by
The method htmlEncode() does not exist on yii\helpers\Json. Did you maybe mean encode()?

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...
201
            $attributes = Json::htmlEncode($this->attributes);
0 ignored issues
show
Bug introduced by
The method htmlEncode() does not exist on yii\helpers\Json. Did you maybe mean encode()?

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...
202
            $view = $this->getView();
203
            ActiveFormAsset::register($view);
204
            $view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
205
        }
206
        if ($this->fake) {
207
            echo Html::endTag('div');
208
        } else {
209
            echo Html::endForm();
210
        }
211
    }
212
213
214
    /**
215
     * Generates a form field.
216
     * A form field is associated with a model and an attribute. It contains a label, an input and an error message
217
     * and use them to interact with end users to collect their inputs for the attribute.
218
     *
219
     * @param Model $model
220
     *        the data model
221
     * @param string $attribute
222
     *        the attribute name or expression. See [[Html::getAttributeName()]] for the format
223
     *        about attribute expression.
224
     * @param array $options
225
     *        the additional configurations for the field object
226
     * @return ActiveField the created ActiveField object
227
     * @see fieldConfig
228
     */
229
    public function field($model, $attribute, $options = [])
230
    {
231
        return parent::field($model, $attribute, $options);
232
    }
233
234
235
    protected function renderActions($currentPosition)
236
    {
237
        $position = ArrayHelper::getValue($this->buttons, 'position', self::BUTTONS_POSITION_BOTTOM);
238
        if (!empty($this->buttons['items']) && $position == $currentPosition) {
239
            $actionsOptions = ArrayHelper::getValue($this->buttons, 'options', []);
240
            Html::addCssClass($actionsOptions, 'form-actions');
241
            if ($position == self::BUTTONS_POSITION_TOP) {
242
                Html::addCssClass($actionsOptions, 'top');
243
            }
244
            if (isset($this->buttons['align']) && $this->buttons['align'] == self::BUTTONS_ALIGN_RIGHT) {
245
                Html::addCssClass($actionsOptions, 'right');
246
            }
247
            $rowOptions = [];
248
            $buttons = implode("\n", $this->buttons['items']);
249
            switch ($this->type) {
250
                case self::TYPE_HORIZONTAL:
251
                    Html::addCssClass($actionsOptions, 'fluid');
252
                    preg_match('#col-md-(\d+)#', $this->fieldConfig['labelOptions']['class'], $matches);
253
                    if (isset($matches[1])) {
254
                        $offset = $matches[1];
255
                        Html::addCssClass($rowOptions, 'col-md-offset-' . $offset);
256
                        Html::addCssClass($rowOptions, 'col-md-' . 12 - $offset);
257
                        $buttons = Html::tag('div', $buttons, $rowOptions);
258
                    }
259
                    break;
260
            }
261
            return Html::tag('div', $buttons, $actionsOptions);
262
        }
263
        return '';
264
    }
265
266
    /**
267
     * Check if form has been set as edit locked
268
     *
269
     * @return boolean
270
     */
271
    public function isEditLocked()
272
    {
273
        return $this->editLocked;
274
    }
275
}
276
277