1
+ <?php
2
+
3
+ namespace ArondeParon \RequestSanitizer \Traits ;
4
+
5
+ use ArondeParon \RequestSanitizer \Contracts \Sanitizer ;
6
+
7
+ trait SanitizesInputs
8
+ {
9
+ /**
10
+ * Get data to be validated from the request.
11
+ *
12
+ * @return array
13
+ */
14
+ protected function validationData ()
15
+ {
16
+ // Sanitize data before passing it to the validator.
17
+ $ this ->sanitize ();
18
+
19
+ return $ this ->all ();
20
+ }
21
+
22
+ public function sanitize ()
23
+ {
24
+ $ input = $ this ->all ();
25
+
26
+ if (!property_exists ($ this , 'sanitizers ' )) {
27
+ $ this ->sanitizers = [];
28
+ }
29
+
30
+ foreach ($ this ->sanitizers as $ formKey => $ sanitizers ) {
31
+ $ sanitizers = (array ) $ sanitizers ;
32
+ foreach ($ sanitizers as $ sanitizer ) {
33
+ if (is_string ($ sanitizer )) {
34
+ $ sanitizer = app ()->make ($ sanitizer );
35
+ }
36
+ $ input [$ formKey ] = $ sanitizer ->sanitize ($ input [$ formKey ] ?? null );
37
+ }
38
+ }
39
+
40
+ return $ this ->replace ($ input );
41
+ }
42
+
43
+ /**
44
+ * Add a single sanitizer.
45
+ *
46
+ * @param string $formKey
47
+ * @param Sanitizer $sanitizer
48
+ * @return $this
49
+ */
50
+ public function addSanitizer (string $ formKey , $ sanitizer )
51
+ {
52
+ if (!isset ($ this ->sanitizers [$ formKey ])) {
53
+ $ this ->sanitizers [$ formKey ] = [];
54
+ }
55
+
56
+ $ this ->sanitizers [$ formKey ][] = $ sanitizer ;
57
+
58
+ return $ this ;
59
+ }
60
+
61
+ /**
62
+ * Add multiple sanitizers.
63
+ *
64
+ * @param $formKey
65
+ * @param array $sanitizers
66
+ * @return $this
67
+ */
68
+ public function addSanitizers ($ formKey , $ sanitizers = [])
69
+ {
70
+ foreach ($ sanitizers as $ sanitizer ) {
71
+ $ this ->addSanitizer ($ formKey , $ sanitizer );
72
+ }
73
+
74
+ return $ this ;
75
+ }
76
+
77
+ /**
78
+ * @param null $formKey
79
+ * @return array
80
+ */
81
+ public function getSanitizers ($ formKey = null )
82
+ {
83
+ if ($ formKey !== null ) {
84
+ return $ this ->sanitizers [$ formKey ] ?? [];
85
+ }
86
+
87
+ return $ this ->sanitizers ;
88
+ }
89
+ }
0 commit comments