Completed
Pull Request — master (#350)
by
unknown
01:31
created

JsValidatorFactory::setOptions()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 8
nop 1
crap 4
1
<?php
2
3
    namespace Isrenato\JsValidation;
4
5
    use Illuminate\Contracts\Validation\Factory as ValidationFactory;
6
    use Illuminate\Support\Arr;
7
    use Illuminate\Validation\Validator;
8
    use Isrenato\JsValidation\Javascript\JavascriptValidator;
9
    use Isrenato\JsValidation\Javascript\MessageParser;
10
    use Isrenato\JsValidation\Javascript\RuleParser;
11
    use Isrenato\JsValidation\Javascript\ValidatorHandler;
12
    use Isrenato\JsValidation\Support\DelegatedValidator;
13
    use Isrenato\JsValidation\Support\ValidationRuleParserProxy;
14
15
    class JsValidatorFactory
16
    {
17
        /**
18
         * The application instance.
19
         *
20
         * @var \Illuminate\Container\Container
21
         */
22
        protected $app;
23
        /**
24
         * Configuration options.
25
         *
26
         * @var array
27
         */
28
        protected $options;
29
        /**
30
         * Create a new Validator factory instance.
31
         *
32
         * @param \Illuminate\Container\Container $app
33
         * @param array                           $options
34
         */
35
        public function __construct($app, array $options = [])
36 84
        {
37
            $this->app = $app;
38 84
            $this->setOptions($options);
39 84
        }
40 84
        /**
41
         * @param $options
42 84
         *
43
         * @return void
44 84
         */
45 84
        protected function setOptions($options)
46 84
        {
47
            $options['disable_remote_validation'] = empty($options['disable_remote_validation']) ? false : $options['disable_remote_validation'];
48 84
            $options['view']                      = empty($options['view']) ? 'jsvalidation:bootstrap' : $options['view'];
49 84
            $options['form_selector']             = empty($options['form_selector']) ? 'form' : $options['form_selector'];
50
            $this->options = $options;
51
        }
52
        /**
53
         * Creates JsValidator instance based on rules and message arrays.
54
         *
55
         * @param array       $rules
56
         * @param array       $messages
57
         * @param array       $customAttributes
58
         * @param null|string $selector
59
         *
60
         * @return \Proengsoft\JsValidation\Javascript\JavascriptValidator
61 48
         */
62
        public function make(array $rules, array $messages = [], array $customAttributes = [], $selector = null)
63 48
        {
64
            $validator = $this->getValidatorInstance($rules, $messages, $customAttributes);
65 48
66
            return str_replace('[#]', '[*]', $this->validator($validator, $selector)->render());
67
        }
68
        /**
69
         * Get the validator instance for the request.
70
         *
71
         * @param array $rules
72
         * @param array $messages
73
         * @param array $customAttributes
74
         *
75
         * @return \Illuminate\Validation\Validator
76 72
         */
77
        protected function getValidatorInstance(array $rules, array $messages = [], array $customAttributes = [])
78 72
        {
79
            $factory = $this->app->make(ValidationFactory::class);
80 72
            $data      = $this->getValidationData($rules, $customAttributes);
81 72
            $validator = $factory->make($data, $rules, $messages, $customAttributes);
82 72
            $validator->addCustomAttributes($customAttributes);
83
            return $validator;
84 72
        }
85
        /**
86
         * Gets fake data when validator has wildcard rules.
87
         *
88
         * @param array $rules
89
         *
90
         * @return array
91
         */
92
        protected function getValidationData(array $rules, array $customAttributes = [])
93 72
        {
94
            $attributes = array_filter(array_keys($rules), function ($attribute) {
95
                return $attribute !== '' && mb_strpos($attribute, '*') !== false;
96 48
            });
97 72
            $attributes = array_merge(array_keys($customAttributes), $attributes);
98
            $attributes = str_replace('*', '#', $attributes);
99 72
            $data       = array_reduce($attributes, function ($data, $attribute) {
100 72
                Arr::set($data, $attribute, true);
101 24
                return $data;
102
            }, []);
103 24
            return $data;
104 72
        }
105
        /**
106 72
         * Creates JsValidator instance based on FormRequest.
107
         *
108
         * @param      $formRequest
109
         * @param null $selector
110
         *
111
         * @return \Proengsoft\JsValidation\Javascript\JavascriptValidator
112
         *
113
         * @throws \Illuminate\Contracts\Container\BindingResolutionException
114
         */
115
        public function formRequest($formRequest, $selector = null)
116
        {
117
            if (!is_object($formRequest)) {
118 24
                $formRequest = $this->createFormRequest($formRequest);
119
            }
120 24
            $rules = method_exists($formRequest, 'rules') ? $formRequest->rules() : [];
121 12
            $validator = $this->getValidatorInstance($rules, $formRequest->messages(), $formRequest->attributes());
122 8
            return $this->validator($validator, $selector);
123
        }
124 24
        /**
125
         * @param string|array $class
126 24
         *
127
         * @return array
128 24
         */
129
        protected function parseFormRequestName($class)
130
        {
131 12
            $params = [];
132
            if (is_array($class)) {
133 12
                $params = empty($class[1]) ? $params : $class[1];
134 12
                $class  = $class[0];
135 12
            }
136 12
            return [$class, $params];
137 8
        }
138
        /**
139 12
         * Creates and initializes an Form Request instance.
140
         *
141
         * @param string $class
142
         *
143
         * @return \Illuminate\Foundation\Http\FormRequest
144
         *
145
         * @throws \Illuminate\Contracts\Container\BindingResolutionException
146
         */
147
        protected function createFormRequest($class)
148 12
        {
149
            /*
150
             * @var $formRequest \Illuminate\Foundation\Http\FormRequest
151
             * @var $request Request
152
             */
153
            list($class, $params) = $this->parseFormRequestName($class);
154 12
            $request     = $this->app->__get('request');
155
            $formRequest = $this->app->build($class, $params);
0 ignored issues
show
Unused Code introduced by
The call to Container::build() has too many arguments starting with $params.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
156 12
            if ($session = $request->getSession()) {
157 12
                $formRequest->setLaravelSession($session);
158
            }
159 12
            $formRequest->setUserResolver($request->getUserResolver());
160 12
            $formRequest->setRouteResolver($request->getRouteResolver());
161 8
            $formRequest->setContainer($this->app);
162 12
            $formRequest->query = $request->query;
163 12
            return $formRequest;
164 12
        }
165 12
        /**
166
         * Creates JsValidator instance based on Validator.
167 12
         *
168
         * @param \Illuminate\Validation\Validator $validator
169
         * @param null|string                      $selector
170
         *
171
         * @return \Proengsoft\JsValidation\Javascript\JavascriptValidator
172
         */
173
        public function validator(Validator $validator, $selector = null)
174
        {
175
            return $this->jsValidator($validator, $selector);
176
        }
177
        /**
178 72
         * Creates JsValidator instance based on Validator.
179
         *
180 72
         * @param \Illuminate\Validation\Validator $validator
181
         * @param null|string                      $selector
182
         *
183
         * @return \Proengsoft\JsValidation\Javascript\JavascriptValidator
184
         */
185
        protected function jsValidator(Validator $validator, $selector = null)
186
        {
187
            $remote   = !$this->options['disable_remote_validation'];
188
            $view     = $this->options['view'];
189
            $selector = is_null($selector) ? $this->options['form_selector'] : $selector;
190
            $delegated = new DelegatedValidator($validator, new ValidationRuleParserProxy());
191 72
            $rules     = new RuleParser($delegated, $this->getSessionToken());
192
            $messages  = new MessageParser($delegated);
193 72
            $jsValidator = new ValidatorHandler($rules, $messages);
194 72
            $manager = new JavascriptValidator($jsValidator, compact('view', 'selector', 'remote'));
195 72
            return $manager;
196
        }
197 72
        /**
198 72
         * Get and encrypt token from session store.
199 72
         *
200
         * @return null|string
201 72
         */
202
        protected function getSessionToken()
203 72
        {
204
            $token = null;
205 72
            if ($session = $this->app->__get('session')) {
206
                $token = $session->token();
207
            }
208
            if ($encrypter = $this->app->__get('encrypter')) {
209
                $token = $encrypter->encrypt($token);
210
            }
211
            return $token;
212
        }
213
    }
214