1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Proengsoft\JsValidation\Remote; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Validation\Validator; |
|
|
|
|
6
|
|
|
use Illuminate\Foundation\Http\FormRequest as Request; |
7
|
|
|
use Illuminate\Http\Exceptions\HttpResponseException; |
8
|
|
|
use Illuminate\Http\JsonResponse; |
9
|
|
|
use Illuminate\Validation\ValidationException; |
10
|
|
|
|
11
|
|
|
class FormRequest extends Request |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Field to identify requests originating from this library. |
15
|
|
|
*/ |
16
|
|
|
const JS_VALIDATION_FIELD = '__proengsoft_form_request'; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Validate the class instance. |
20
|
|
|
* |
21
|
|
|
* @return void |
22
|
|
|
*/ |
23
|
|
|
public function validateResolved() |
24
|
|
|
{ |
25
|
|
|
parent::validateResolved(); |
26
|
|
|
|
27
|
|
|
// BC for Laravel versions prior to 6.x. |
28
|
|
|
$this->passedValidation(); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Handle a passed validation attempt. |
33
|
|
|
* |
34
|
|
|
* @return void |
35
|
|
|
*/ |
36
|
|
|
protected function passedValidation() |
37
|
|
|
{ |
38
|
|
|
if ($this->isJsValidation()) { |
39
|
|
|
throw new HttpResponseException( |
40
|
|
|
new JsonResponse(true, 200) |
41
|
|
|
); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
parent::passedValidation(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Handle a failed validation attempt. |
49
|
|
|
* |
50
|
|
|
* @param \Illuminate\Contracts\Validation\Validator $validator |
51
|
|
|
* @return void |
52
|
|
|
* |
53
|
|
|
* @throws \Illuminate\Validation\ValidationException |
54
|
|
|
*/ |
55
|
|
|
protected function failedValidation(Validator $validator) |
56
|
|
|
{ |
57
|
|
|
if ($this->isJsValidation()) { |
58
|
|
|
throw new ValidationException( |
59
|
|
|
$validator, |
60
|
|
|
new JsonResponse($validator->errors()->messages(), 200) |
61
|
|
|
); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
parent::failedValidation($validator); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Whether the request originated from laravel-jsvalidation. |
69
|
|
|
* |
70
|
|
|
* @return bool |
71
|
|
|
*/ |
72
|
|
|
private function isJsValidation() |
73
|
|
|
{ |
74
|
|
|
return $this->has(static::JS_VALIDATION_FIELD); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: