Completed
Pull Request — master (#348)
by
unknown
13:10
created

RemoteValidationMiddleware::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Isrenato\JsValidation;
4
5
use Closure;
6
use Illuminate\Contracts\Config\Repository as Config;
7
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
8
use Illuminate\Http\Request;
9
use Isrenato\JsValidation\Remote\Resolver;
10
use Isrenato\JsValidation\Remote\Validator as RemoteValidator;
11
12
class RemoteValidationMiddleware
13
{
14
    /**
15
     * Validator factory instance to wrap.
16
     *
17
     * @var \Illuminate\Contracts\Validation\Factory
18
     */
19
    protected $factory;
20
21
    /**
22
     * Field used to detect Javascript validation.
23
     *
24
     * @var mixed
25
     */
26
    protected $field;
27
28
    /**
29
     * RemoteValidationMiddleware constructor.
30
     *
31
     * @param \Illuminate\Contracts\Validation\Factory $validator
32
     * @param \Illuminate\Contracts\Config\Repository $config
33
     */
34 24
    public function __construct(ValidationFactory $validator, Config $config)
35
    {
36 24
        $this->factory = $validator;
37 24
        $this->field = $config->get('jsvalidation.remote_validation_field');
38 24
    }
39
40
    /**
41
     * Handle an incoming request.
42
     *
43
     * @param \Illuminate\Http\Request $request
44
     * @param \Closure $next
45
     * @return mixed
46
     */
47
    public function handle(Request $request, Closure $next)
48 24
    {
49
        if ($request->has($this->field)) {
50 24
            $this->wrapValidator();
51 12
        }
52 8
53
        return $next($request);
54 24
    }
55
56
    /**
57
     * Wraps Validator resolver with RemoteValidator resolver.
58
     *
59
     * @return void
60 12
     */
61
    protected function wrapValidator()
62 12
    {
63 12
        $resolver = new Resolver($this->factory);
64 12
        $this->factory->resolver($resolver->resolver($this->field));
65 12
        $this->factory->extend(RemoteValidator::EXTENSION_NAME, $resolver->validatorClosure());
66
    }
67
}
68