1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace RealPage\JsonApi\Validation; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Validation\Factory; |
6
|
|
|
use Neomerx\JsonApi\Exceptions\ErrorCollection; |
7
|
|
|
use RealPage\JsonApi\Requests\Request; |
8
|
|
|
use Neomerx\JsonApi\Document\Error; |
9
|
|
|
|
10
|
|
|
abstract class ValidatesRequests |
11
|
|
|
{ |
12
|
|
|
/** @var ErrorCollection */ |
13
|
|
|
protected $errors; |
14
|
|
|
|
15
|
|
|
/** @var Factory */ |
16
|
|
|
protected $validatorFactory; |
17
|
|
|
|
18
|
6 |
|
public function isValid(Request $request) : bool |
19
|
|
|
{ |
20
|
6 |
|
$this->errors = new ErrorCollection(); |
21
|
|
|
|
22
|
|
|
/** @var \Illuminate\Contracts\Validation\Validator $validator */ |
23
|
6 |
|
$validator = $this->validatorFactory->make($request->json(), $this->rules(), $this->messages()); |
24
|
6 |
|
if ($validator->fails()) { |
25
|
|
|
// @todo put this somewhere else, this is getting messy |
26
|
|
|
// @see https://jsonapi.org/examples/#error-objects-basic |
27
|
3 |
|
foreach ($validator->errors()->toArray() as $field => $errorMessages) { |
28
|
|
|
|
29
|
|
|
// get the pointer for an array so we can pinpoint the section |
30
|
|
|
// of json where the error occurred |
31
|
3 |
|
$field = '/'.str_replace('.', '/', $field).'/'; |
32
|
|
|
|
33
|
3 |
|
foreach ($errorMessages as $message) { |
34
|
3 |
|
$this->errors->add(new Error( |
35
|
3 |
|
null, |
36
|
3 |
|
null, |
37
|
3 |
|
422, |
38
|
3 |
|
null, |
39
|
3 |
|
'Invalid Attribute', |
40
|
3 |
|
$message, |
41
|
|
|
[ |
42
|
3 |
|
'pointer' => $field, |
43
|
|
|
] |
44
|
|
|
)); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
3 |
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
return true; |
52
|
|
|
} |
53
|
|
|
|
54
|
9 |
|
public function rules() : array |
55
|
|
|
{ |
56
|
|
|
return [ |
57
|
9 |
|
'data' => 'required', |
58
|
9 |
|
'data.type' => 'required|in:'.$this->type(), |
59
|
|
|
]; |
60
|
|
|
} |
61
|
|
|
|
62
|
9 |
|
public function messages() : array |
63
|
|
|
{ |
64
|
|
|
return [ |
65
|
9 |
|
'data.required' => 'Data is required in a valid json api format.', |
66
|
9 |
|
'data.type.required' => 'A valid resource type must be provided.', |
67
|
9 |
|
'data.type.in' => 'The resource type provided does not match the expected type of "'.$this->type().'".', |
68
|
|
|
]; |
69
|
|
|
} |
70
|
|
|
|
71
|
6 |
|
public function errors() : ErrorCollection |
72
|
|
|
{ |
73
|
6 |
|
return $this->errors; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* The type of entity this request is for. |
78
|
|
|
*/ |
79
|
|
|
abstract public function type() : string; |
80
|
|
|
|
81
|
6 |
|
public function setValidatorFactory(Factory $factory) |
82
|
|
|
{ |
83
|
6 |
|
$this->validatorFactory = $factory; |
84
|
6 |
|
} |
85
|
|
|
} |
86
|
|
|
|