Validation::filterReset()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace FFCMS\Traits;
4
5
use FFMVC\Helpers as Helpers;
6
7
/**
8
 * Handle validation (via GUMP or GUMP-inheriting validation class)
9
 *
10
 * The constructor should optional initialise default validation and filtering rules.
11
 * The class can then call the default method validate() which return true/false if validation passed
12
 * or validate(false) which returns an array of the validation errors which can be made
13
 * more presentable passed into validationErrors()
14
 *
15
 * @see \FFCMS\Helpers\Validator
16
 * @url https://github.com/Wixel/GUMP
17
 */
18
trait Validation
19
{
20
    /**
21
     * Validation rules (GUMP rules array)
22
     *
23
     * @var array
24
     */
25
    protected $validationRules = [];
26
27
    /**
28
     * Initial validation rules (automatically copied from $validationRules when instantiated)
29
     *
30
     * @var array
31
     */
32
    protected $validationRulesDefault = [];
33
34
    /**
35
     * Filter rules  (GUMP filters array)
36
     *
37
     * @var array
38
     */
39
    protected $filterRules = [];
40
41
    /**
42
     * Initial filter rules  (automatically copied from $filterRules when instantiated)
43
     *
44
     * @var array
45
     */
46
    protected $filterRulesDefault = [];
47
48
    /**
49
     * Boolean flag from validation run results if object is valid
50
     *
51
     * @var boolean
52
     */
53
    protected $valid = false;
54
55
    /**
56
     * Errors from last validation run
57
     *
58
     * @var bool|array
59
     */
60
    protected $validationErrors;
61
62
63
    /**
64
     * initialize
65
     */
66
    public function __construct()
67
    {
68
        // save default validation rules and filter rules in-case we add rules
69
        $this->validationRulesDefault = $this->validationRules;
70
        $this->filterRulesDefault = $this->filterRules;
71
    }
72
73
74
    /**
75
     * Get filter rules array
76
     *
77
     * @return array
78
     */
79
    public function filterRulesGet(): array
80
    {
81
        return $this->filterRules;
82
    }
83
84
85
    /**
86
     * Get default filter rules array
87
     *
88
     * @return array
89
     */
90
    public function filterRulesDefault(): array
91
    {
92
        return $this->filterRulesDefault;
93
    }
94
95
96
    /**
97
     * Get validation rules array
98
     *
99
     * @return array
100
     */
101
    public function validationRulesGet(): array
102
    {
103
        return $this->validationRules;
104
    }
105
106
107
    /**
108
     * Get default validation rules array
109
     *
110
     * @return array
111
     */
112
    public function validationRulesDefault(): array
113
    {
114
        return $this->validationRulesDefault;
115
    }
116
117
118
    /**
119
     * Set filter rules from array
120
     *
121
     * @param array $rules
122
     * @return array
123
     */
124
    public function filterRules(array $rules = []): array
125
    {
126
        $this->filterRules = $rules;
127
128
        return $this->filterRules;
129
    }
130
131
132
    /**
133
     * Set validation rules from array
134
     *
135
     * @param array $rules
136
     * @return array
137
     */
138
    public function validationRules(array $rules = []): array
139
    {
140
        $this->validationRules = $rules;
141
142
        return $this->validationRules;
143
    }
144
145
146
    /**
147
     * Reset filter rules to default
148
     *
149
     * @return array
150
     */
151
    public function filterReset(): array
152
    {
153
        $this->filterRules = $this->filterRulesDefault;
154
155
        return $this->filterRules;
156
    }
157
158
159
    /**
160
     * Reset validation rules to default
161
     *
162
     * @return array
163
     */
164
    public function validationReset(): array
165
    {
166
        $this->validationRules = $this->validationRulesDefault;
167
168
        return $this->validationRules;
169
    }
170
171
172
    /**
173
     * Add extra filter rules from array
174
     *
175
     * @param array $rules
176
     * @return array
177
     */
178
    public function filterRulesAdd(array $rules = []): array
179
    {
180
        $this->filterRules = array_merge($this->filterRules, $rules);
181
182
        return $this->filterRules;
183
    }
184
185
186
    /**
187
     * Add extra validation rules from array
188
     *
189
     * @param array $rules
190
     * @return array
191
     */
192
    public function validationRulesAdd(array $rules = []): array
193
    {
194
        $this->validationRules = array_merge($this->validationRules, $rules);
195
196
        return $this->validationRules;
197
    }
198
199
200
    /**
201
     * Enforce validation required validation check on given fields
202
     * or all fields if no array passed in
203
     *
204
     * @param array optional $fields
205
     * @return array $validationRules
206
     */
207
    public function validationRequired(array $fields = []): array
208
    {
209
        $rules = $this->validationRules;
210
211
        // force all fields to required if empty
212
        if (empty($fields)) {
213
            $fields = array_keys($rules);
214
        }
215
216
        // appened 'required' to validation rules for fields
217
        foreach ($rules as $k => $v) {
218
            if (in_array($k, $fields)) {
219
                $rules[$k] = 'required|' . $v;
220
            } elseif (false !== \UTF::instance()->stristr($v, 'exact_len')) {
221
                // special case, exact_len means required otherwise!
222
                unset($rules[$k]);
223
            }
224
        }
225
226
        $this->validationRules = $rules;
227
228
        return $this->validationRules;
229
    }
230
231
232
    /**
233
     * Apply filter rules only
234
     *
235
     * @param array $data
236
     * @param array $rules
237
     * @return array $data
238
     */
239
    public function filter(array $data = [], array $rules = []): array
240
    {
241
        if (empty($data) && method_exists($this, 'cast')) {
242
            $data = $this->cast();
243
        }
244
245
        $validator = Helpers\Validator::instance();
246
        $validator->filter_rules(empty($rules) ? $this->filterRules : $rules);
247
        return $validator->filter($data);
248
    }
249
250
251
    /**
252
     * Filter, then validate
253
     *
254
     * @param boolean $run GUMP - call 'run' (return true/false) otherwise call 'validate' (return array of errors)
255
     * @param array $data optional data array if different values to check outside of this mapper object fields
256
     * @param array $validationRules
257
     * @param array $filterRules
258
     * @return boolean|array of validated data if 'run' otherwise array of errors or boolean if passed 'validate'
259
     * @link https://github.com/Wixel/GUMP
260
     */
261
    public function validate($run = true, array $data = [], array $validationRules = [], array $filterRules = [])
262
    {
263
        if (empty($data) && method_exists($this, 'cast')) {
264
            $data = $this->cast();
265
        }
266
267
        $validator = Helpers\Validator::instance();
268
        $validator->validation_rules(empty($validationRules) ? $this->validationRules : $validationRules);
269
        $validator->filter_rules(empty($filterRules) ? $this->filterRules : $filterRules);
270
271
        if (!empty($run)) {
272
            // return boolean success/failure after validation
273
            $this->valid = is_array($validator->run($validator->filter($data)));
274
            return $this->valid;
275
        } else {
276
            // return array of errors if fail rathern than false
277
            $this->validationErrors = $validator->validate($validator->filter($data));
278
            $this->valid = !is_array($this->validationErrors);
279
            return $this->valid ? true : $this->validationErrors;
280
        }
281
    }
282
283
284
    /**
285
     * Process errors of results from (return array of $this->validate(true)) $validator->run($data) into friendlier notifications
286
     *
287
     * @param mixed $errors errors from $validator->run($data) or get last errors
288
     * @return array $notifications
289
     */
290
    public function validationErrors($errors = []): array
291
    {
292
        if (empty($errors)) {
293
            $errors = $this->validationErrors;
294
            if (empty($errors)) {
295
                return [];
296
            }
297
        }
298
299
        $notifications = [];
300
301
        if (is_array($errors)) {
302
            foreach ($errors as $e) {
303
                $fieldname = ucwords(str_replace('_', ' ', $e['field']));
304
305
                switch ($e['rule']) {
306
307
                    case 'validate_exact_len':
308
                        $msg = sprintf(_('%s must be exactly %d characters in length.'),
309
                            $fieldname, $e['param']);
310
                        break;
311
312
                    case 'validate_min_len':
313
                        $msg = sprintf(_('%s must be at least %d characters.'),
314
                            $fieldname, $e['param']);
315
                        break;
316
317
                    case 'validate_max_len':
318
                        $msg = sprintf(_('%s must at most %d characters.'),
319
                            $fieldname, $e['param']);
320
                        break;
321
322
                    case 'validate_valid_url':
323
                        $msg = sprintf('URLs must be valid if set.', $fieldname);
324
                        break;
325
326
                    case 'validate_valid_email':
327
                        $msg = sprintf(_('%s must be a valid email address.'),
328
                            $fieldname);
329
                        break;
330
331
                    case 'validate_required':
332
                        $msg = sprintf(_('%s must be entered.'), $fieldname);
333
                        break;
334
335
                    case 'validate_valid_name':
336
                        $msg = sprintf(_('%s must be a valid name.'),
337
                            $fieldname);
338
                        break;
339
340
                    case 'validate_boolean':
341
                        $msg = sprintf(_('%s must be a valid boolean (0/1 false/true off/on yes/no).'),
342
                            $fieldname);
343
                        break;
344
345
                    default:
346
                        $msg = sprintf('Exception: %s %s %s', $fieldname,
347
                            $e['rule'], $e['param']);
348
                        break;
349
                }
350
                $notifications[] = $msg;
351
            }
352
        }
353
        return $notifications;
354
    }
355
}
356