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 — master ( 533da6...33cff4 )
by Robert
08:57
created

ActiveForm::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\widgets;
9
10
use Yii;
11
use yii\base\InvalidCallException;
12
use yii\base\Widget;
13
use yii\base\Model;
14
use yii\helpers\ArrayHelper;
15
use yii\helpers\Url;
16
use yii\helpers\Html;
17
use yii\helpers\Json;
18
19
/**
20
 * ActiveForm is a widget that builds an interactive HTML form for one or multiple data models.
21
 *
22
 * For more details and usage information on ActiveForm, see the [guide article on forms](guide:input-forms).
23
 *
24
 * @author Qiang Xue <[email protected]>
25
 * @since 2.0
26
 */
27
class ActiveForm extends Widget
28
{
29
    /**
30
     * @var array|string the form action URL. This parameter will be processed by [[\yii\helpers\Url::to()]].
31
     * @see method for specifying the HTTP method for this form.
32
     */
33
    public $action = '';
34
    /**
35
     * @var string the form submission method. This should be either `post` or `get`. Defaults to `post`.
36
     *
37
     * When you set this to `get` you may see the url parameters repeated on each request.
38
     * This is because the default value of [[action]] is set to be the current request url and each submit
39
     * will add new parameters instead of replacing existing ones.
40
     * You may set [[action]] explicitly to avoid this:
41
     *
42
     * ```php
43
     * $form = ActiveForm::begin([
44
     *     'method' => 'get',
45
     *     'action' => ['controller/action'],
46
     * ]);
47
     * ```
48
     */
49
    public $method = 'post';
50
    /**
51
     * @var array the HTML attributes (name-value pairs) for the form tag.
52
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
53
     */
54
    public $options = [];
55
    /**
56
     * @var string the default field class name when calling [[field()]] to create a new field.
57
     * @see fieldConfig
58
     */
59
    public $fieldClass = 'yii\widgets\ActiveField';
60
    /**
61
     * @var array|\Closure the default configuration used by [[field()]] when creating a new field object.
62
     * This can be either a configuration array or an anonymous function returning a configuration array.
63
     * If the latter, the signature should be as follows:
64
     *
65
     * ```php
66
     * function ($model, $attribute)
67
     * ```
68
     *
69
     * The value of this property will be merged recursively with the `$options` parameter passed to [[field()]].
70
     *
71
     * @see fieldClass
72
     */
73
    public $fieldConfig = [];
74
    /**
75
     * @var bool whether to perform encoding on the error summary.
76
     */
77
    public $encodeErrorSummary = true;
78
    /**
79
     * @var string the default CSS class for the error summary container.
80
     * @see errorSummary()
81
     */
82
    public $errorSummaryCssClass = 'error-summary';
83
    /**
84
     * @var string the CSS class that is added to a field container when the associated attribute is required.
85
     */
86
    public $requiredCssClass = 'required';
87
    /**
88
     * @var string the CSS class that is added to a field container when the associated attribute has validation error.
89
     */
90
    public $errorCssClass = 'has-error';
91
    /**
92
     * @var string the CSS class that is added to a field container when the associated attribute is successfully validated.
93
     */
94
    public $successCssClass = 'has-success';
95
    /**
96
     * @var string the CSS class that is added to a field container when the associated attribute is being validated.
97
     */
98
    public $validatingCssClass = 'validating';
99
    /**
100
     * @var bool whether to enable client-side data validation.
101
     * If [[ActiveField::enableClientValidation]] is set, its value will take precedence for that input field.
102
     */
103
    public $enableClientValidation = true;
104
    /**
105
     * @var bool whether to enable AJAX-based data validation.
106
     * If [[ActiveField::enableAjaxValidation]] is set, its value will take precedence for that input field.
107
     */
108
    public $enableAjaxValidation = false;
109
    /**
110
     * @var bool whether to hook up `yii.activeForm` JavaScript plugin.
111
     * This property must be set `true` if you want to support client validation and/or AJAX validation, or if you
112
     * want to take advantage of the `yii.activeForm` plugin. When this is `false`, the form will not generate
113
     * any JavaScript.
114
     * @see registerClientScript
115
     */
116
    public $enableClientScript = true;
117
    /**
118
     * @var array|string the URL for performing AJAX-based validation. This property will be processed by
119
     * [[Url::to()]]. Please refer to [[Url::to()]] for more details on how to configure this property.
120
     * If this property is not set, it will take the value of the form's action attribute.
121
     */
122
    public $validationUrl;
123
    /**
124
     * @var bool whether to perform validation when the form is submitted.
125
     */
126
    public $validateOnSubmit = true;
127
    /**
128
     * @var bool whether to perform validation when the value of an input field is changed.
129
     * If [[ActiveField::validateOnChange]] is set, its value will take precedence for that input field.
130
     */
131
    public $validateOnChange = true;
132
    /**
133
     * @var bool whether to perform validation when an input field loses focus.
134
     * If [[ActiveField::$validateOnBlur]] is set, its value will take precedence for that input field.
135
     */
136
    public $validateOnBlur = true;
137
    /**
138
     * @var bool whether to perform validation while the user is typing in an input field.
139
     * If [[ActiveField::validateOnType]] is set, its value will take precedence for that input field.
140
     * @see validationDelay
141
     */
142
    public $validateOnType = false;
143
    /**
144
     * @var int number of milliseconds that the validation should be delayed when the user types in the field
145
     * and [[validateOnType]] is set `true`.
146
     * If [[ActiveField::validationDelay]] is set, its value will take precedence for that input field.
147
     */
148
    public $validationDelay = 500;
149
    /**
150
     * @var string the name of the GET parameter indicating the validation request is an AJAX request.
151
     */
152
    public $ajaxParam = 'ajax';
153
    /**
154
     * @var string the type of data that you're expecting back from the server.
155
     */
156
    public $ajaxDataType = 'json';
157
    /**
158
     * @var bool whether to scroll to the first error after validation.
159
     * @since 2.0.6
160
     */
161
    public $scrollToError = true;
162
    /**
163
     * @var int offset in pixels that should be added when scrolling to the first error.
164
     * @since 2.0.11
165
     */
166
    public $scrollToErrorOffset = 0;
167
    /**
168
     * @var array the client validation options for individual attributes. Each element of the array
169
     * represents the validation options for a particular attribute.
170
     * @internal
171
     */
172
    public $attributes = [];
173
174
    /**
175
     * @var ActiveField[] the ActiveField objects that are currently active
176
     */
177
    private $_fields = [];
178
179
180
    /**
181
     * Initializes the widget.
182
     * This renders the form open tag.
183
     */
184 32
    public function init()
185
    {
186 32
        if (!isset($this->options['id'])) {
187 32
            $this->options['id'] = $this->getId();
188
        }
189 32
        ob_start();
190 32
        ob_implicit_flush(false);
191 32
    }
192
193
    /**
194
     * Runs the widget.
195
     * This registers the necessary JavaScript code and renders the form open and close tags.
196
     * @throws InvalidCallException if `beginField()` and `endField()` calls are not matching.
197
     */
198 32
    public function run()
199
    {
200 32
        if (!empty($this->_fields)) {
201
            throw new InvalidCallException('Each beginField() should have a matching endField() call.');
202
        }
203
204 32
        $content = ob_get_clean();
205 32
        echo Html::beginForm($this->action, $this->method, $this->options);
206 32
        echo $content;
207
208 32
        if ($this->enableClientScript) {
209 1
            $this->registerClientScript();
210
        }
211
212 32
        echo Html::endForm();
213 32
    }
214
215
    /**
216
     * This registers the necessary JavaScript code.
217
     * @since 2.0.12
218
     */
219 1
    public function registerClientScript()
220
    {
221 1
        $id = $this->options['id'];
222 1
        $options = Json::htmlEncode($this->getClientOptions());
223 1
        $attributes = Json::htmlEncode($this->attributes);
224 1
        $view = $this->getView();
225 1
        ActiveFormAsset::register($view);
226 1
        $view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
227 1
    }
228
229
    /**
230
     * Returns the options for the form JS widget.
231
     * @return array the options.
232
     */
233 1
    protected function getClientOptions()
234
    {
235
        $options = [
236 1
            'encodeErrorSummary' => $this->encodeErrorSummary,
237 1
            'errorSummary' => '.' . implode('.', preg_split('/\s+/', $this->errorSummaryCssClass, -1, PREG_SPLIT_NO_EMPTY)),
238 1
            'validateOnSubmit' => $this->validateOnSubmit,
239 1
            'errorCssClass' => $this->errorCssClass,
240 1
            'successCssClass' => $this->successCssClass,
241 1
            'validatingCssClass' => $this->validatingCssClass,
242 1
            'ajaxParam' => $this->ajaxParam,
243 1
            'ajaxDataType' => $this->ajaxDataType,
244 1
            'scrollToError' => $this->scrollToError,
245 1
            'scrollToErrorOffset' => $this->scrollToErrorOffset,
246
        ];
247 1
        if ($this->validationUrl !== null) {
248
            $options['validationUrl'] = Url::to($this->validationUrl);
249
        }
250
251
        // only get the options that are different from the default ones (set in yii.activeForm.js)
252 1
        return array_diff_assoc($options, [
253 1
            'encodeErrorSummary' => true,
254
            'errorSummary' => '.error-summary',
255
            'validateOnSubmit' => true,
256
            'errorCssClass' => 'has-error',
257
            'successCssClass' => 'has-success',
258
            'validatingCssClass' => 'validating',
259
            'ajaxParam' => 'ajax',
260
            'ajaxDataType' => 'json',
261
            'scrollToError' => true,
262
            'scrollToErrorOffset' => 0,
263
        ]);
264
    }
265
266
    /**
267
     * Generates a summary of the validation errors.
268
     * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
269
     * @param Model|Model[] $models the model(s) associated with this form.
270
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
271
     *
272
     * - `header`: string, the header HTML for the error summary. If not set, a default prompt string will be used.
273
     * - `footer`: string, the footer HTML for the error summary.
274
     *
275
     * The rest of the options will be rendered as the attributes of the container tag. The values will
276
     * be HTML-encoded using [[\yii\helpers\Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
277
     * @return string the generated error summary.
278
     * @see errorSummaryCssClass
279
     */
280
    public function errorSummary($models, $options = [])
281
    {
282
        Html::addCssClass($options, $this->errorSummaryCssClass);
283
        $options['encode'] = $this->encodeErrorSummary;
284
        return Html::errorSummary($models, $options);
285
    }
286
287
    /**
288
     * Generates a form field.
289
     * A form field is associated with a model and an attribute. It contains a label, an input and an error message
290
     * and use them to interact with end users to collect their inputs for the attribute.
291
     * @param Model $model the data model.
292
     * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
293
     * about attribute expression.
294
     * @param array $options the additional configurations for the field object. These are properties of [[ActiveField]]
295
     * or a subclass, depending on the value of [[fieldClass]].
296
     * @return ActiveField the created ActiveField object.
297
     * @see fieldConfig
298
     */
299 4
    public function field($model, $attribute, $options = [])
300
    {
301 4
        $config = $this->fieldConfig;
302 4
        if ($config instanceof \Closure) {
303
            $config = call_user_func($config, $model, $attribute);
304
        }
305 4
        if (!isset($config['class'])) {
306 4
            $config['class'] = $this->fieldClass;
307
        }
308 4
        return Yii::createObject(ArrayHelper::merge($config, $options, [
309 4
            'model' => $model,
310 4
            'attribute' => $attribute,
311 4
            'form' => $this,
312
        ]));
313
    }
314
315
    /**
316
     * Begins a form field.
317
     * This method will create a new form field and returns its opening tag.
318
     * You should call [[endField()]] afterwards.
319
     * @param Model $model the data model.
320
     * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
321
     * about attribute expression.
322
     * @param array $options the additional configurations for the field object.
323
     * @return string the opening tag.
324
     * @see endField()
325
     * @see field()
326
     */
327
    public function beginField($model, $attribute, $options = [])
328
    {
329
        $field = $this->field($model, $attribute, $options);
330
        $this->_fields[] = $field;
331
        return $field->begin();
332
    }
333
334
    /**
335
     * Ends a form field.
336
     * This method will return the closing tag of an active form field started by [[beginField()]].
337
     * @return string the closing tag of the form field.
338
     * @throws InvalidCallException if this method is called without a prior [[beginField()]] call.
339
     */
340
    public function endField()
341
    {
342
        $field = array_pop($this->_fields);
343
        if ($field instanceof ActiveField) {
344
            return $field->end();
345
        } else {
346
            throw new InvalidCallException('Mismatching endField() call.');
347
        }
348
    }
349
350
    /**
351
     * Validates one or several models and returns an error message array indexed by the attribute IDs.
352
     * This is a helper method that simplifies the way of writing AJAX validation code.
353
     *
354
     * For example, you may use the following code in a controller action to respond
355
     * to an AJAX validation request:
356
     *
357
     * ```php
358
     * $model = new Post;
359
     * $model->load(Yii::$app->request->post());
360
     * if (Yii::$app->request->isAjax) {
361
     *     Yii::$app->response->format = Response::FORMAT_JSON;
362
     *     return ActiveForm::validate($model);
363
     * }
364
     * // ... respond to non-AJAX request ...
365
     * ```
366
     *
367
     * To validate multiple models, simply pass each model as a parameter to this method, like
368
     * the following:
369
     *
370
     * ```php
371
     * ActiveForm::validate($model1, $model2, ...);
372
     * ```
373
     *
374
     * @param Model $model the model to be validated.
375
     * @param mixed $attributes list of attributes that should be validated.
376
     * If this parameter is empty, it means any attribute listed in the applicable
377
     * validation rules should be validated.
378
     *
379
     * When this method is used to validate multiple models, this parameter will be interpreted
380
     * as a model.
381
     *
382
     * @return array the error message array indexed by the attribute IDs.
383
     */
384
    public static function validate($model, $attributes = null)
385
    {
386
        $result = [];
387
        if ($attributes instanceof Model) {
388
            // validating multiple models
389
            $models = func_get_args();
390
            $attributes = null;
391
        } else {
392
            $models = [$model];
393
        }
394
        /* @var $model Model */
395
        foreach ($models as $model) {
396
            $model->validate($attributes);
397
            foreach ($model->getErrors() as $attribute => $errors) {
398
                $result[Html::getInputId($model, $attribute)] = $errors;
399
            }
400
        }
401
402
        return $result;
403
    }
404
405
    /**
406
     * Validates an array of model instances and returns an error message array indexed by the attribute IDs.
407
     * This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
408
     *
409
     * For example, you may use the following code in a controller action to respond
410
     * to an AJAX validation request:
411
     *
412
     * ```php
413
     * // ... load $models ...
414
     * if (Yii::$app->request->isAjax) {
415
     *     Yii::$app->response->format = Response::FORMAT_JSON;
416
     *     return ActiveForm::validateMultiple($models);
417
     * }
418
     * // ... respond to non-AJAX request ...
419
     * ```
420
     *
421
     * @param array $models an array of models to be validated.
422
     * @param mixed $attributes list of attributes that should be validated.
423
     * If this parameter is empty, it means any attribute listed in the applicable
424
     * validation rules should be validated.
425
     * @return array the error message array indexed by the attribute IDs.
426
     */
427
    public static function validateMultiple($models, $attributes = null)
428
    {
429
        $result = [];
430
        /* @var $model Model */
431
        foreach ($models as $i => $model) {
432
            $model->validate($attributes);
433
            foreach ($model->getErrors() as $attribute => $errors) {
434
                $result[Html::getInputId($model, "[$i]" . $attribute)] = $errors;
435
            }
436
        }
437
438
        return $result;
439
    }
440
}
441