forked from octobercms/library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidation.php
More file actions
371 lines (308 loc) · 10.7 KB
/
Validation.php
File metadata and controls
371 lines (308 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php namespace October\Rain\Halcyon\Traits;
use Illuminate\Support\Arr;
use Illuminate\Support\MessageBag;
use October\Rain\Halcyon\Exception\ModelException;
use October\Rain\Support\Facades\Input;
use Validator;
use Exception;
trait Validation
{
/**
* @var array rules to be applied to the data.
*
* public $rules = [];
*/
/**
* @var array attributeNames of custom attributes
*
* public $attributeNames = [];
*/
/**
* @var array customMessages of custom error messages
*
* public $customMessages = [];
*/
/**
* @var bool throwOnValidation makes the validation procedure throw an {@link October\Rain\Database\ModelException}
* instead of returning false when validation fails
*
* public $throwOnValidation = true;
*/
/**
* @var \Illuminate\Support\MessageBag validationErrors message bag
*/
protected $validationErrors;
/**
* @var \Illuminate\Validation\Validator validator instance
*/
protected static $validator;
/**
* bootValidation trait for this model.
*/
public static function bootValidation()
{
if (!property_exists(static::class, 'rules')) {
throw new Exception(sprintf('You must define a $rules property in %s to use the Validation trait.', static::class));
}
static::extend(function ($model) {
$model->bindEvent('model.saveInternal', function ($data, $options) use ($model) {
// If forcing the save event, the beforeValidate/afterValidate
// events should still fire for consistency. So validate an
// empty set of rules and messages.
$force = Arr::get($options, 'force', false);
if ($force) {
$valid = $model->validate([], []);
}
else {
$valid = $model->validate();
}
if (!$valid) {
return false;
}
}, 500);
});
}
/**
* getValidationAttributes returns the model data used for validation.
* @return array
*/
protected function getValidationAttributes()
{
return $this->getAttributes();
}
/**
* makeValidator instantiates the validator used by the validation process, depending if the class is being used inside or
* outside of Laravel.
* @return \Illuminate\Validation\Validator
*/
protected static function makeValidator($data, $rules, $customMessages, $attributeNames)
{
return static::getModelValidator()->make($data, $rules, $customMessages, $attributeNames);
}
/**
* forceSave the model even if validation fails.
* @return bool
*/
public function forceSave($options = null)
{
return $this->saveInternal(['force' => true] + (array) $options);
}
/**
* validate the model instance
* @return bool
*/
public function validate($rules = null, $customMessages = null, $attributeNames = null)
{
if ($this->validationErrors === null) {
$this->validationErrors = new MessageBag;
}
$throwOnValidation = property_exists($this, 'throwOnValidation')
? $this->throwOnValidation
: true;
if (($this->fireModelEvent('validating') === false) || ($this->fireEvent('model.beforeValidate') === false)) {
if ($throwOnValidation) {
throw new ModelException($this);
}
return false;
}
if ($this->methodExists('beforeValidate')) {
$this->beforeValidate();
}
// Perform validation
$rules = is_null($rules) ? $this->rules : $rules;
$rules = $this->processValidationRules($rules);
$success = true;
if (!empty($rules)) {
$data = $this->getValidationAttributes();
$lang = static::getModelValidator()->getTranslator();
// Custom messages, translate internal references
if (property_exists($this, 'customMessages') && is_null($customMessages)) {
$customMessages = $this->customMessages;
}
if (is_null($customMessages)) {
$customMessages = [];
}
$translatedCustomMessages = [];
foreach ($customMessages as $rule => $customMessage) {
$translatedCustomMessages[$rule] = $lang->get($customMessage);
}
$customMessages = $translatedCustomMessages;
// Attribute names, translate internal references
if (is_null($attributeNames)) {
$attributeNames = [];
}
if (property_exists($this, 'attributeNames')) {
$attributeNames = array_merge($this->attributeNames, $attributeNames);
}
$translatedAttributeNames = [];
foreach ($attributeNames as $attribute => $attributeName) {
$translatedAttributeNames[$attribute] = $lang->get($attributeName);
}
$attributeNames = $translatedAttributeNames;
// Translate any externally defined attribute names
$translations = $lang->get('validation.attributes');
if (is_array($translations)) {
$attributeNames = array_merge($translations, $attributeNames);
}
// Hand over to the validator
$validator = static::makeValidator($data, $rules, $customMessages, $attributeNames);
$success = $validator->passes();
if ($success) {
if ($this->validationErrors->count() > 0) {
$this->validationErrors = new MessageBag;
}
}
else {
$this->validationErrors = $validator->messages();
// Flash input, if available
if (
($input = Input::getFacadeRoot()) &&
method_exists($input, 'hasSession') &&
$input->hasSession()
) {
$input->flash();
}
}
}
$this->fireModelEvent('validated', false);
$this->fireEvent('model.afterValidate');
if ($this->methodExists('afterValidate')) {
$this->afterValidate();
}
if (!$success && $throwOnValidation) {
throw new ModelException($this);
}
return $success;
}
/**
* processValidationRules
*/
protected function processValidationRules($rules)
{
// Run through field names and convert array notation field names to dot notation
$rules = $this->processRuleFieldNames($rules);
foreach ($rules as $field => $ruleParts) {
// Trim empty rules
if (is_string($ruleParts) && trim($ruleParts) === '') {
unset($rules[$field]);
continue;
}
// Normalize rulesets
if (!is_array($ruleParts)) {
$ruleParts = explode('|', $ruleParts);
}
// Analyse each rule individually
foreach ($ruleParts as $key => $rulePart) {
// Look for required:create and required:update rules
if (str_starts_with($rulePart, 'required:create') && $this->exists) {
unset($ruleParts[$key]);
}
elseif (str_starts_with($rulePart, 'required:update') && !$this->exists) {
unset($ruleParts[$key]);
}
}
$rules[$field] = $ruleParts;
}
return $rules;
}
/**
* processRuleFieldNames converts any field names using array notation
* (ie. `field[child]`) into dot notation (ie. `field.child`)
* @param array $rules
* @return array
*/
protected function processRuleFieldNames($rules)
{
$processed = [];
foreach ($rules as $field => $ruleParts) {
$fieldName = $field;
if (preg_match('/^.*?\[.*?\]/', $fieldName)) {
$fieldName = str_replace('[]', '.*', $fieldName);
$fieldName = str_replace(['[', ']'], ['.', ''], $fieldName);
}
$processed[$fieldName] = $ruleParts;
}
return $processed;
}
/**
* isAttributeRequired determines if an attribute is required based on the validation rules.
* @param string $attribute
* @return bool
*/
public function isAttributeRequired($attribute)
{
if (!isset($this->rules[$attribute])) {
return false;
}
$ruleset = $this->rules[$attribute];
if (is_array($ruleset)) {
$ruleset = implode('|', $ruleset);
}
if (strpos($ruleset, 'required:create') !== false && $this->exists) {
return false;
}
if (strpos($ruleset, 'required:update') !== false && !$this->exists) {
return false;
}
if (strpos($ruleset, 'required_with') !== false) {
$requiredWith = substr($ruleset, strpos($ruleset, 'required_with') + 14);
$requiredWith = substr($requiredWith, 0, strpos($requiredWith, '|'));
return $this->isAttributeRequired($requiredWith);
}
return strpos($ruleset, 'required') !== false;
}
/**
* errors gets validation error message collection for the Model
* @return \Illuminate\Support\MessageBag
*/
public function errors()
{
return $this->validationErrors;
}
/**
* validating creates a new native event for handling beforeValidate().
* @param Closure|string $callback
* @return void
*/
public static function validating($callback)
{
static::registerModelEvent('validating', $callback);
}
/**
* validated creates a new native event for handling afterValidate().
* @param Closure|string $callback
* @return void
*/
public static function validated($callback)
{
static::registerModelEvent('validated', $callback);
}
/**
* getModelValidator instance.
* @return \Illuminate\Validation\Validator
*/
public static function getModelValidator()
{
if (static::$validator === null) {
static::$validator = Validator::getFacadeRoot();
}
return static::$validator;
}
/**
* setModelValidator instance.
* @param \Illuminate\Validation\Validator
* @return void
*/
public static function setModelValidator($validator)
{
static::$validator = $validator;
}
/**
* unsetModelValidator for models.
* @return void
*/
public static function unsetModelValidator()
{
static::$validator = null;
}
}