Complex classes like Validator 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 Validator, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
56 | class Validator extends Component |
||
57 | { |
||
58 | /** |
||
59 | * @var array list of built-in validators (name => class or configuration) |
||
60 | */ |
||
61 | public static $builtInValidators = [ |
||
62 | 'boolean' => 'yii\validators\BooleanValidator', |
||
63 | 'captcha' => 'yii\captcha\CaptchaValidator', |
||
64 | 'compare' => 'yii\validators\CompareValidator', |
||
65 | 'date' => 'yii\validators\DateValidator', |
||
66 | 'datetime' => [ |
||
67 | 'class' => 'yii\validators\DateValidator', |
||
68 | 'type' => DateValidator::TYPE_DATETIME, |
||
69 | ], |
||
70 | 'time' => [ |
||
71 | 'class' => 'yii\validators\DateValidator', |
||
72 | 'type' => DateValidator::TYPE_TIME, |
||
73 | ], |
||
74 | 'default' => 'yii\validators\DefaultValueValidator', |
||
75 | 'double' => 'yii\validators\NumberValidator', |
||
76 | 'each' => 'yii\validators\EachValidator', |
||
77 | 'email' => 'yii\validators\EmailValidator', |
||
78 | 'exist' => 'yii\validators\ExistValidator', |
||
79 | 'file' => 'yii\validators\FileValidator', |
||
80 | 'filter' => 'yii\validators\FilterValidator', |
||
81 | 'image' => 'yii\validators\ImageValidator', |
||
82 | 'in' => 'yii\validators\RangeValidator', |
||
83 | 'integer' => [ |
||
84 | 'class' => 'yii\validators\NumberValidator', |
||
85 | 'integerOnly' => true, |
||
86 | ], |
||
87 | 'match' => 'yii\validators\RegularExpressionValidator', |
||
88 | 'number' => 'yii\validators\NumberValidator', |
||
89 | 'required' => 'yii\validators\RequiredValidator', |
||
90 | 'safe' => 'yii\validators\SafeValidator', |
||
91 | 'string' => 'yii\validators\StringValidator', |
||
92 | 'trim' => [ |
||
93 | 'class' => 'yii\validators\FilterValidator', |
||
94 | 'filter' => 'trim', |
||
95 | 'skipOnArray' => true, |
||
96 | ], |
||
97 | 'unique' => 'yii\validators\UniqueValidator', |
||
98 | 'url' => 'yii\validators\UrlValidator', |
||
99 | 'ip' => 'yii\validators\IpValidator', |
||
100 | ]; |
||
101 | /** |
||
102 | * @var array|string attributes to be validated by this validator. For multiple attributes, |
||
103 | * please specify them as an array; for single attribute, you may use either a string or an array. |
||
104 | */ |
||
105 | public $attributes = []; |
||
106 | /** |
||
107 | * @var string the user-defined error message. It may contain the following placeholders which |
||
108 | * will be replaced accordingly by the validator: |
||
109 | * |
||
110 | * - `{attribute}`: the label of the attribute being validated |
||
111 | * - `{value}`: the value of the attribute being validated |
||
112 | * |
||
113 | * Note that some validators may introduce other properties for error messages used when specific |
||
114 | * validation conditions are not met. Please refer to individual class API documentation for details |
||
115 | * about these properties. By convention, this property represents the primary error message |
||
116 | * used when the most important validation condition is not met. |
||
117 | */ |
||
118 | public $message; |
||
119 | /** |
||
120 | * @var array|string scenarios that the validator can be applied to. For multiple scenarios, |
||
121 | * please specify them as an array; for single scenario, you may use either a string or an array. |
||
122 | */ |
||
123 | public $on = []; |
||
124 | /** |
||
125 | * @var array|string scenarios that the validator should not be applied to. For multiple scenarios, |
||
126 | * please specify them as an array; for single scenario, you may use either a string or an array. |
||
127 | */ |
||
128 | public $except = []; |
||
129 | /** |
||
130 | * @var bool whether this validation rule should be skipped if the attribute being validated |
||
131 | * already has some validation error according to some previous rules. Defaults to true. |
||
132 | */ |
||
133 | public $skipOnError = true; |
||
134 | /** |
||
135 | * @var bool whether this validation rule should be skipped if the attribute value |
||
136 | * is null or an empty string. |
||
137 | */ |
||
138 | public $skipOnEmpty = true; |
||
139 | /** |
||
140 | * @var bool whether to enable client-side validation for this validator. |
||
141 | * The actual client-side validation is done via the JavaScript code returned |
||
142 | * by [[clientValidateAttribute()]]. If that method returns null, even if this property |
||
143 | * is true, no client-side validation will be done by this validator. |
||
144 | */ |
||
145 | public $enableClientValidation = true; |
||
146 | /** |
||
147 | * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]]. |
||
148 | * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature |
||
149 | * of the callable should be `function ($value)` which returns a boolean indicating |
||
150 | * whether the value is empty. |
||
151 | */ |
||
152 | public $isEmpty; |
||
153 | /** |
||
154 | * @var callable a PHP callable whose return value determines whether this validator should be applied. |
||
155 | * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute` |
||
156 | * refer to the model and the attribute currently being validated. The callable should return a boolean value. |
||
157 | * |
||
158 | * This property is mainly provided to support conditional validation on the server-side. |
||
159 | * If this property is not set, this validator will be always applied on the server-side. |
||
160 | * |
||
161 | * The following example will enable the validator only when the country currently selected is USA: |
||
162 | * |
||
163 | * ```php |
||
164 | * function ($model) { |
||
165 | * return $model->country == Country::USA; |
||
166 | * } |
||
167 | * ``` |
||
168 | * |
||
169 | * @see whenClient |
||
170 | */ |
||
171 | public $when; |
||
172 | /** |
||
173 | * @var string a JavaScript function name whose return value determines whether this validator should be applied |
||
174 | * on the client-side. The signature of the function should be `function (attribute, value)`, where |
||
175 | * `attribute` is an object describing the attribute being validated (see [[clientValidateAttribute()]]) |
||
176 | * and `value` the current value of the attribute. |
||
177 | * |
||
178 | * This property is mainly provided to support conditional validation on the client-side. |
||
179 | * If this property is not set, this validator will be always applied on the client-side. |
||
180 | * |
||
181 | * The following example will enable the validator only when the country currently selected is USA: |
||
182 | * |
||
183 | * ```javascript |
||
184 | * function (attribute, value) { |
||
185 | * return $('#country').val() === 'USA'; |
||
186 | * } |
||
187 | * ``` |
||
188 | * |
||
189 | * @see when |
||
190 | */ |
||
191 | public $whenClient; |
||
192 | |||
193 | |||
194 | /** |
||
195 | * Creates a validator object. |
||
196 | * @param string|\Closure $type the validator type. This can be either: |
||
197 | * * a built-in validator name listed in [[builtInValidators]]; |
||
198 | * * a method name of the model class; |
||
199 | * * an anonymous function; |
||
200 | * * a validator class name. |
||
201 | * @param \yii\base\Model $model the data model to be validated. |
||
202 | * @param array|string $attributes list of attributes to be validated. This can be either an array of |
||
203 | * the attribute names or a string of comma-separated attribute names. |
||
204 | * @param array $params initial values to be applied to the validator properties. |
||
205 | * @return Validator the validator |
||
206 | */ |
||
207 | 42 | public static function createValidator($type, $model, $attributes, $params = []) |
|
208 | { |
||
209 | 42 | $params['attributes'] = $attributes; |
|
210 | |||
211 | 42 | if ($type instanceof \Closure || $model->hasMethod($type)) { |
|
212 | // method-based validator |
||
213 | 3 | $params['class'] = __NAMESPACE__ . '\InlineValidator'; |
|
214 | 3 | $params['method'] = $type; |
|
215 | } else { |
||
216 | 40 | if (isset(static::$builtInValidators[$type])) { |
|
217 | 36 | $type = static::$builtInValidators[$type]; |
|
218 | } |
||
219 | 40 | if (is_array($type)) { |
|
220 | 11 | $params = array_merge($type, $params); |
|
221 | } else { |
||
222 | 34 | $params['class'] = $type; |
|
223 | } |
||
224 | } |
||
225 | |||
226 | 42 | return Yii::createObject($params); |
|
227 | } |
||
228 | |||
229 | /** |
||
230 | * @inheritdoc |
||
231 | */ |
||
232 | 402 | public function init() |
|
233 | { |
||
234 | 402 | parent::init(); |
|
235 | 402 | $this->attributes = (array) $this->attributes; |
|
236 | 402 | $this->on = (array) $this->on; |
|
237 | 402 | $this->except = (array) $this->except; |
|
238 | 402 | } |
|
239 | |||
240 | /** |
||
241 | * Validates the specified object. |
||
242 | * @param \yii\base\Model $model the data model being validated |
||
243 | * @param array|null $attributes the list of attributes to be validated. |
||
244 | * Note that if an attribute is not associated with the validator - it will be |
||
245 | * ignored. If this parameter is null, every attribute listed in [[attributes]] will be validated. |
||
246 | */ |
||
247 | 18 | public function validateAttributes($model, $attributes = null) |
|
248 | { |
||
249 | 18 | if (is_array($attributes)) { |
|
250 | 16 | $newAttributes = []; |
|
251 | 16 | $attributeNames = $this->getAttributeNames(); |
|
252 | 16 | foreach ($attributes as $attribute) { |
|
253 | 16 | if (in_array($attribute, $attributeNames, true)) { |
|
254 | 15 | $newAttributes[] = $attribute; |
|
255 | } |
||
256 | } |
||
257 | 16 | $attributes = $newAttributes; |
|
258 | } else { |
||
259 | 4 | $attributes = $this->getAttributeNames(); |
|
260 | } |
||
261 | |||
262 | 18 | foreach ($attributes as $attribute) { |
|
263 | 17 | $skip = $this->skipOnError && $model->hasErrors($attribute) |
|
264 | 17 | || $this->skipOnEmpty && $this->isEmpty($model->$attribute); |
|
265 | 17 | if (!$skip) { |
|
266 | 12 | if ($this->when === null || call_user_func($this->when, $model, $attribute)) { |
|
267 | 12 | $this->validateAttribute($model, $attribute); |
|
268 | } |
||
269 | } |
||
270 | } |
||
271 | 18 | } |
|
272 | |||
273 | /** |
||
274 | * Validates a single attribute. |
||
275 | * Child classes must implement this method to provide the actual validation logic. |
||
276 | * @param \yii\base\Model $model the data model to be validated |
||
277 | * @param string $attribute the name of the attribute to be validated. |
||
278 | */ |
||
279 | 12 | public function validateAttribute($model, $attribute) |
|
280 | { |
||
281 | 12 | $result = $this->validateValue($model->$attribute); |
|
282 | 12 | if (!empty($result)) { |
|
283 | 7 | $this->addError($model, $attribute, $result[0], $result[1]); |
|
284 | } |
||
285 | 12 | } |
|
286 | |||
287 | /** |
||
288 | * Validates a given value. |
||
289 | * You may use this method to validate a value out of the context of a data model. |
||
290 | * @param mixed $value the data value to be validated. |
||
291 | * @param string $error the error message to be returned, if the validation fails. |
||
292 | * @return bool whether the data is valid. |
||
293 | */ |
||
294 | 96 | public function validate($value, &$error = null) |
|
295 | { |
||
296 | 96 | $result = $this->validateValue($value); |
|
297 | 91 | if (empty($result)) { |
|
298 | 59 | return true; |
|
299 | } |
||
300 | |||
301 | 79 | list($message, $params) = $result; |
|
302 | 79 | $params['attribute'] = Yii::t('yii', 'the input value'); |
|
303 | 79 | if (is_array($value)) { |
|
304 | 12 | $params['value'] = 'array()'; |
|
305 | 74 | } elseif (is_object($value)) { |
|
306 | 5 | $params['value'] = 'object'; |
|
307 | } else { |
||
308 | 69 | $params['value'] = $value; |
|
309 | } |
||
310 | 79 | $error = $this->formatMessage($message, $params); |
|
311 | |||
312 | 79 | return false; |
|
313 | } |
||
314 | |||
315 | /** |
||
316 | * Validates a value. |
||
317 | * A validator class can implement this method to support data validation out of the context of a data model. |
||
318 | * @param mixed $value the data value to be validated. |
||
319 | * @return array|null the error message and the parameters to be inserted into the error message. |
||
320 | * Null should be returned if the data is valid. |
||
321 | * @throws NotSupportedException if the validator does not supporting data validation without a model |
||
322 | */ |
||
323 | 1 | protected function validateValue($value) |
|
327 | |||
328 | /** |
||
329 | * Returns the JavaScript needed for performing client-side validation. |
||
330 | * |
||
331 | * Calls [[getClientOptions()]] to generate options array for client-side validation. |
||
332 | * |
||
333 | * You may override this method to return the JavaScript validation code if |
||
334 | * the validator can support client-side validation. |
||
335 | * |
||
336 | * The following JavaScript variables are predefined and can be used in the validation code: |
||
337 | * |
||
338 | * - `attribute`: an object describing the the attribute being validated. |
||
339 | * - `value`: the value being validated. |
||
340 | * - `messages`: an array used to hold the validation error messages for the attribute. |
||
341 | * - `deferred`: an array used to hold deferred objects for asynchronous validation |
||
342 | * - `$form`: a jQuery object containing the form element |
||
343 | * |
||
344 | * The `attribute` object contains the following properties: |
||
345 | * - `id`: a unique ID identifying the attribute (e.g. "loginform-username") in the form |
||
346 | * - `name`: attribute name or expression (e.g. "[0]content" for tabular input) |
||
347 | * - `container`: the jQuery selector of the container of the input field |
||
348 | * - `input`: the jQuery selector of the input field under the context of the form |
||
349 | * - `error`: the jQuery selector of the error tag under the context of the container |
||
350 | * - `status`: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating |
||
351 | * |
||
352 | * @param \yii\base\Model $model the data model being validated |
||
353 | * @param string $attribute the name of the attribute to be validated. |
||
354 | * @param \yii\web\View $view the view object that is going to be used to render views or view files |
||
355 | * containing a model form with this validator applied. |
||
356 | * @return string|null the client-side validation script. Null if the validator does not support |
||
357 | * client-side validation. |
||
358 | * @see getClientOptions() |
||
359 | * @see \yii\widgets\ActiveForm::enableClientValidation |
||
360 | */ |
||
361 | 1 | public function clientValidateAttribute($model, $attribute, $view) |
|
365 | |||
366 | /** |
||
367 | * Returns the client-side validation options. |
||
368 | * This method is usually called from [[clientValidateAttribute()]]. You may override this method to modify options |
||
369 | * that will be passed to the client-side validation. |
||
370 | * @param \yii\base\Model $model the model being validated |
||
371 | * @param string $attribute the attribute name being validated |
||
372 | * @return array the client-side validation options |
||
373 | * @since 2.0.11 |
||
374 | */ |
||
375 | public function getClientOptions($model, $attribute) |
||
379 | |||
380 | /** |
||
381 | * Returns a value indicating whether the validator is active for the given scenario and attribute. |
||
382 | * |
||
383 | * A validator is active if |
||
384 | * |
||
385 | * - the validator's `on` property is empty, or |
||
386 | * - the validator's `on` property contains the specified scenario |
||
387 | * |
||
388 | * @param string $scenario scenario name |
||
389 | * @return bool whether the validator applies to the specified scenario. |
||
390 | */ |
||
391 | 26 | public function isActive($scenario) |
|
395 | |||
396 | /** |
||
397 | * Adds an error about the specified attribute to the model object. |
||
398 | * This is a helper method that performs message selection and internationalization. |
||
399 | * @param \yii\base\Model $model the data model being validated |
||
400 | * @param string $attribute the attribute being validated |
||
401 | * @param string $message the error message |
||
402 | * @param array $params values for the placeholders in the error message |
||
403 | */ |
||
404 | 92 | public function addError($model, $attribute, $message, $params = []) |
|
405 | { |
||
406 | 92 | $params['attribute'] = $model->getAttributeLabel($attribute); |
|
407 | 92 | if (!isset($params['value'])) { |
|
408 | 92 | $value = $model->$attribute; |
|
409 | 92 | if (is_array($value)) { |
|
410 | 28 | $params['value'] = 'array()'; |
|
411 | 90 | } elseif (is_object($value) && !method_exists($value, '__toString')) { |
|
412 | 1 | $params['value'] = '(object)'; |
|
413 | } else { |
||
414 | 90 | $params['value'] = $value; |
|
415 | } |
||
416 | } |
||
417 | 92 | $model->addError($attribute, $this->formatMessage($message, $params)); |
|
418 | 92 | } |
|
419 | |||
420 | /** |
||
421 | * Checks if the given value is empty. |
||
422 | * A value is considered empty if it is null, an empty array, or an empty string. |
||
423 | * Note that this method is different from PHP empty(). It will return false when the value is 0. |
||
424 | * @param mixed $value the value to be checked |
||
425 | * @return bool whether the value is empty |
||
426 | */ |
||
427 | 166 | public function isEmpty($value) |
|
435 | |||
436 | /** |
||
437 | * Formats a mesage using the I18N, or simple strtr if `\Yii::$app` is not available. |
||
438 | * @param string $message |
||
439 | * @param array $params |
||
440 | * @since 2.0.12 |
||
441 | * @return string |
||
442 | */ |
||
443 | 171 | protected function formatMessage($message, $params) |
|
444 | { |
||
445 | 171 | if (Yii::$app !== null) { |
|
446 | 50 | return \Yii::$app->getI18n()->format($message, $params, Yii::$app->language); |
|
447 | } |
||
448 | |||
449 | 121 | $placeholders = []; |
|
450 | 121 | foreach ((array) $params as $name => $value) { |
|
451 | 121 | $placeholders['{' . $name . '}'] = $value; |
|
452 | } |
||
453 | |||
454 | 121 | return ($placeholders === []) ? $message : strtr($message, $placeholders); |
|
455 | } |
||
456 | |||
457 | /** |
||
458 | * Returns cleaned attribute names without the `!` character at the beginning |
||
459 | * @return array attribute names. |
||
460 | * @since 2.0.12 |
||
461 | */ |
||
462 | public function getAttributeNames() |
||
468 | } |
||
469 |