ValidatesWhenResolvedTrait.php 2.2 KB

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