| 1 | <?php |
||
| 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 |
|
| 61 | |||
| 62 | 9 | public function messages() : array |
|
| 70 | |||
| 71 | 6 | public function errors() : ErrorCollection |
|
| 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) |
|
| 85 | } |
||
| 86 |