ValidatesWhenResolvedTrait.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace Illuminate\Validation;
  3. /**
  4. * Provides default implementation of ValidatesWhenResolved contract.
  5. */
  6. trait ValidatesWhenResolvedTrait
  7. {
  8. /**
  9. * Validate the class instance.
  10. *
  11. * @return void
  12. */
  13. public function validateResolved()
  14. {
  15. $this->prepareForValidation();
  16. if (! $this->passesAuthorization()) {
  17. $this->failedAuthorization();
  18. }
  19. $instance = $this->getValidatorInstance();
  20. if (! $instance->passes()) {
  21. $this->failedValidation($instance);
  22. }
  23. }
  24. /**
  25. * Prepare the data for validation.
  26. *
  27. * @return void
  28. */
  29. protected function prepareForValidation()
  30. {
  31. // no default action
  32. }
  33. /**
  34. * Get the validator instance for the request.
  35. *
  36. * @return \Illuminate\Validation\Validator
  37. */
  38. protected function getValidatorInstance()
  39. {
  40. return $this->validator();
  41. }
  42. /**
  43. * Handle a failed validation attempt.
  44. *
  45. * @param \Illuminate\Validation\Validator $validator
  46. * @return void
  47. *
  48. * @throws \Illuminate\Validation\ValidationException
  49. */
  50. protected function failedValidation(Validator $validator)
  51. {
  52. throw new ValidationException($validator);
  53. }
  54. /**
  55. * Determine if the request passes the authorization check.
  56. *
  57. * @return bool
  58. */
  59. protected function passesAuthorization()
  60. {
  61. if (method_exists($this, 'authorize')) {
  62. return $this->authorize();
  63. }
  64. return true;
  65. }
  66. /**
  67. * Handle a failed authorization attempt.
  68. *
  69. * @return void
  70. *
  71. * @throws \Illuminate\Validation\UnauthorizedException
  72. */
  73. protected function failedAuthorization()
  74. {
  75. throw new UnauthorizedException;
  76. }
  77. }