Can.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Illuminate\Validation\Rules;
  3. use Illuminate\Contracts\Validation\Rule;
  4. use Illuminate\Contracts\Validation\ValidatorAwareRule;
  5. use Illuminate\Support\Facades\Gate;
  6. class Can implements Rule, ValidatorAwareRule
  7. {
  8. /**
  9. * The ability to check.
  10. *
  11. * @var string
  12. */
  13. protected $ability;
  14. /**
  15. * The arguments to pass to the authorization check.
  16. *
  17. * @var array
  18. */
  19. protected $arguments;
  20. /**
  21. * The current validator instance.
  22. *
  23. * @var \Illuminate\Validation\Validator
  24. */
  25. protected $validator;
  26. /**
  27. * Constructor.
  28. *
  29. * @param string $ability
  30. * @param array $arguments
  31. */
  32. public function __construct($ability, array $arguments = [])
  33. {
  34. $this->ability = $ability;
  35. $this->arguments = $arguments;
  36. }
  37. /**
  38. * Determine if the validation rule passes.
  39. *
  40. * @param string $attribute
  41. * @param mixed $value
  42. * @return bool
  43. */
  44. public function passes($attribute, $value)
  45. {
  46. $arguments = $this->arguments;
  47. $model = array_shift($arguments);
  48. return Gate::allows($this->ability, array_filter([$model, ...$arguments, $value]));
  49. }
  50. /**
  51. * Get the validation error message.
  52. *
  53. * @return array
  54. */
  55. public function message()
  56. {
  57. $message = $this->validator->getTranslator()->get('validation.can');
  58. return $message === 'validation.can'
  59. ? ['The :attribute field contains an unauthorized value.']
  60. : $message;
  61. }
  62. /**
  63. * Set the current validator.
  64. *
  65. * @param \Illuminate\Validation\Validator $validator
  66. * @return $this
  67. */
  68. public function setValidator($validator)
  69. {
  70. $this->validator = $validator;
  71. return $this;
  72. }
  73. }