Completed
Branch delegated-factory (7f020d)
by Albert
03:05
created

JsValidatorFactory::setOptions()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.2
cc 4
eloc 4
nc 8
nop 1
1
<?php
2
3
namespace Proengsoft\JsValidation;
4
5
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
6
use Illuminate\Foundation\Http\FormRequest;
7
use Illuminate\Http\Request;
8
use Illuminate\Validation\Validator;
9
use Proengsoft\JsValidation\Exceptions\FormRequestArgumentException;
10
use Proengsoft\JsValidation\Javascript\JavascriptValidator;
11
use Proengsoft\JsValidation\Javascript\MessageParser;
12
use Proengsoft\JsValidation\Javascript\RuleParser;
13
use Proengsoft\JsValidation\Javascript\ValidatorHandler;
14
use Proengsoft\JsValidation\Support\DelegatedValidator;
15
16
class JsValidatorFactory
17
{
18
    /**
19
     * The application instance.
20
     *
21
     * @var \Illuminate\Contracts\Container\Container
22
     */
23
    protected $app;
24
25
    /**
26
     * Configuration options.
27
     *
28
     * @var array
29
     */
30
    protected $options;
31
32
    /**
33
     * Create a new Validator factory instance.
34
     *
35
     * @param \Illuminate\Contracts\Container\Container $app
36
     * @param array                                        $options
37
     */
38
    public function __construct($app, array $options = [])
39
    {
40
        $this->app = $app;
41
        $this->setOptions($options);
0 ignored issues
show
Unused Code introduced by
The call to the method Proengsoft\JsValidation\...orFactory::setOptions() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
42
    }
43
44
    protected function setOptions($options) {
45
        $options['disable_remote_validation'] = empty($options['disable_remote_validation'])?false:$options['disable_remote_validation'];
46
        $options['view'] = empty($options['view'])?'jsvalidation:bootstrap':$options['view'];
47
        $options['form_selector'] = empty($options['form_selector'])?'form':$options['form_selector'];
48
    }
49
50
51
    /**
52
     * Creates JsValidator instance based on rules and message arrays.
53
     *
54
     * @param array       $rules
55
     * @param array       $messages
56
     * @param array       $customAttributes
57
     * @param null|string $selector
58
     *
59
     * @return \Proengsoft\JsValidation\Manager
60
     */
61
    public function make(array $rules, array $messages = array(), array $customAttributes = array(), $selector = null)
62
    {
63
        $validator = $this->getValidatorInstance($rules, $messages, $customAttributes);
64
65
        return $this->validator($validator, $selector);
66
    }
67
68
    /**
69
     * Get the validator instance for the request.
70
     *
71
     * @return \Illuminate\Validation\Validator
72
     */
73
    protected function getValidatorInstance(array $rules, array $messages = array(), array $customAttributes = array())
74
    {
75
        $factory = $this->app->make(ValidationFactory::class);
76
77
        $validator = $factory->make([], $rules, $messages, $customAttributes);
78
        $validator->addCustomAttributes($customAttributes);
79
80
        return $validator;
81
    }
82
83
    /**
84
     * Creates JsValidator instance based on FormRequest.
85
     *
86
     * @param $formRequest
87
     * @param null $selector
88
     *
89
     * @return JavascriptValidator
90
     *
91
     * @throws FormRequestArgumentException
92
     */
93
    public function formRequest($formRequest, $selector = null)
94
    {
95
        if (!is_subclass_of($formRequest, 'Illuminate\\Foundation\\Http\\FormRequest')) {
96
            throw new FormRequestArgumentException((string) $formRequest);
97
        }
98
99
        if (is_string($formRequest)) {
100
            $formRequest = $this->createFormRequest($formRequest);
101
        }
102
103
        $rules = method_exists($formRequest, 'rules') ? $formRequest->rules() : [];
104
105
        $validator = $this->getValidatorInstance($rules, $formRequest->messages(), $formRequest->attributes());
106
107
        return $this->validator($validator, $selector);
108
    }
109
110
    /**
111
     *  Creates and initializes an Form Request instance.
112
     *
113
     * @param string $class
114
     *
115
     * @return FormRequest
116
     */
117
    protected function createFormRequest($class)
118
    {
119
        $request = $this->app->__get('request');
120
        $formRequest = call_user_func([$class, 'createFromBase'], $request);
121
122
        if ($session = $request->getSession()) {
123
            $formRequest->setSession($session);
124
        }
125
126
        $formRequest->setUserResolver($request->getUserResolver());
127
128
        $formRequest->setRouteResolver($request->getRouteResolver());
129
130
        return $formRequest;
131
    }
132
133
    /**
134
     * Creates JsValidator instance based on Validator.
135
     *
136
     * @param \Illuminate\Validation\Validator $validator
137
     * @param string|null                      $selector
138
     *
139
     * @return JavascriptValidator
140
     */
141
    public function validator(Validator $validator, $selector = null)
142
    {
143
        return $this->jsValidator($validator, $selector);
144
    }
145
146
    /**
147
     * Creates JsValidator instance based on Validator.
148
     *
149
     * @param \Illuminate\Validation\Validator $validator
150
     * @param string|null                      $selector
151
     *
152
     * @return JavascriptValidator
153
     */
154
    protected function jsValidator(Validator $validator, $selector = null)
155
    {
156
        $remote = !$this->options['disable_remote_validation'];
157
        $view = $this->options['view'];
158
        $selector = is_null($selector) ? $this->options['form_selector'] : $selector;
159
160
        $delegated = new DelegatedValidator($validator);
161
        $rules = new RuleParser($delegated, $this->getSessionToken());
162
        $messages = new MessageParser($delegated);
163
164
        $jsValidator = new ValidatorHandler($rules, $messages);
165
166
        $manager = new JavascriptValidator($jsValidator, compact('view', 'selector', 'remote'));
167
168
        return $manager;
169
    }
170
171
    /**
172
     * Get and encrypt token from session store.
173
     *
174
     * @return null|string
175
     */
176
    protected function getSessionToken()
177
    {
178
        $token = null;
179
        if ($session = $this->app->__get('session')) {
180
            $token = $session->token();
181
        }
182
183
        if ($encrypter = $this->app->__get('encrypter')) {
184
            $token = $encrypter->encrypt($token);
185
        }
186
187
        return $token;
188
    }
189
190
}
191