|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Devlop\Laravel\Validation; |
| 6 | + |
| 7 | +use Illuminate\Contracts\Validation\Validator; |
| 8 | +use Illuminate\Http\Exceptions\HttpResponseException; |
| 9 | +use Illuminate\Validation\ValidationException; |
| 10 | +use Symfony\Component\HttpFoundation\Response; |
| 11 | + |
| 12 | +trait FailedValidationResponse |
| 13 | +{ |
| 14 | + /** |
| 15 | + * Handle a failed validation attempt. |
| 16 | + * |
| 17 | + * @param Validator $validator |
| 18 | + * @return void |
| 19 | + * |
| 20 | + * @throws ValidationException |
| 21 | + */ |
| 22 | + protected function failedValidation(Validator $validator) |
| 23 | + { |
| 24 | + $response = $this->failedValidationResponse($validator); |
| 25 | + |
| 26 | + if ($response) { |
| 27 | + throw new ValidationException($validator, $response); |
| 28 | + } |
| 29 | + |
| 30 | + parent::failedValidation(); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Get the response for a failed validation attempt. |
| 35 | + * |
| 36 | + * @param Validator $validator |
| 37 | + * @return Response|null |
| 38 | + */ |
| 39 | + protected function failedValidationResponse(Validator $validator) : ?Response |
| 40 | + { |
| 41 | + // Implement this method to use a custom response on validation failure. |
| 42 | + // Do not implement this method to instead use the default behaviour. |
| 43 | + |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Handle a failed authorization attempt. |
| 49 | + * |
| 50 | + * @return void |
| 51 | + * |
| 52 | + * @throws HttpResponseException |
| 53 | + * @throws \Illuminate\Validation\UnauthorizedException |
| 54 | + */ |
| 55 | + protected function failedAuthorization() |
| 56 | + { |
| 57 | + $response = $this->failedAuthorizationResponse(); |
| 58 | + |
| 59 | + if ($response) { |
| 60 | + throw new HttpResponseException($response); |
| 61 | + } |
| 62 | + |
| 63 | + // No custom response available, fall back to the default behaviour. |
| 64 | + parent::failedAuthorization(); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Get the response for a failed authorization attempt. |
| 69 | + * |
| 70 | + * @return Response|null |
| 71 | + */ |
| 72 | + protected function failedAuthorizationResponse() : ?Response |
| 73 | + { |
| 74 | + // Implement this method to use a custom response on authorization failure. |
| 75 | + // Do not implement this method to instead use the default behaviour. |
| 76 | + |
| 77 | + return null; |
| 78 | + } |
| 79 | +} |
0 commit comments