1
|
|
|
<?php namespace Arcanedev\Support; |
2
|
|
|
|
3
|
|
|
use Illuminate\Foundation\Http\FormRequest as BaseFormRequest; |
4
|
|
|
use Illuminate\Http\JsonResponse; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Class FormRequest |
8
|
|
|
* |
9
|
|
|
* @package Arcanedev\Support |
10
|
|
|
* @author ARCANEDEV <[email protected]> |
11
|
|
|
*/ |
12
|
|
|
abstract class FormRequest extends BaseFormRequest |
13
|
|
|
{ |
14
|
|
|
/* ----------------------------------------------------------------- |
15
|
|
|
| Main Methods |
16
|
|
|
| ----------------------------------------------------------------- |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Determine if the user is authorized to make this request. |
21
|
|
|
* |
22
|
|
|
* @return bool |
23
|
|
|
*/ |
24
|
|
|
public function authorize() |
25
|
|
|
{ |
26
|
|
|
return false; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Get the validation rules that apply to the request. |
31
|
|
|
* |
32
|
|
|
* @return array |
33
|
|
|
*/ |
34
|
|
|
abstract public function rules(); |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Prepare the data for validation. |
38
|
|
|
*/ |
39
|
|
|
protected function prepareForValidation() |
40
|
|
|
{ |
41
|
|
|
if (method_exists($this, 'sanitize')) { |
42
|
|
|
$this->merge($this->sanitize()); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Get the proper failed validation response for the request. |
48
|
|
|
* |
49
|
|
|
* @param array $errors |
50
|
|
|
* |
51
|
|
|
* @return \Symfony\Component\HttpFoundation\Response |
52
|
|
|
*/ |
53
|
|
|
public function response(array $errors) |
54
|
|
|
{ |
55
|
|
|
return $this->expectsJson() |
56
|
|
|
? new JsonResponse($this->formatJsonErrorsResponse($errors), 422) |
57
|
|
|
: parent::response($errors); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/* ----------------------------------------------------------------- |
61
|
|
|
| Other Methods |
62
|
|
|
| ----------------------------------------------------------------- |
63
|
|
|
*/ |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Format the json response. |
67
|
|
|
* |
68
|
|
|
* @param array $errors |
69
|
|
|
* |
70
|
|
|
* @return array |
71
|
|
|
*/ |
72
|
|
|
protected function formatJsonErrorsResponse(array $errors) |
73
|
|
|
{ |
74
|
|
|
return [ |
75
|
|
|
'code' => 'validation_failed', |
76
|
|
|
'messages' => $errors |
77
|
|
|
]; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
If you implement
__call
and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.This is often the case, when
__call
is implemented by a parent class and only the child class knows which methods exist: