Can.php
TLDR
This file contains the implementation of the Can
class in the Illuminate\Validation\Rules
namespace. The class is a validation rule that checks if a user has the specified ability or permission.
Class Can
The Can
class implements the Rule
and ValidatorAwareRule
interfaces. It has the following properties:
-
$ability
: The ability or permission to check. -
$arguments
: The arguments to pass to the authorization check. -
$validator
: The current validator instance.
The class provides the following methods:
__construct($ability, $arguments = [])
The constructor method initializes the $ability
and $arguments
properties.
-
$ability
: The ability or permission to check. -
$arguments
: An array of arguments to pass to the authorization check.
passes($attribute, $value)
The passes
method determines if the validation rule passes.
-
$attribute
: The name of the attribute being validated. -
$value
: The value of the attribute being validated.
The method uses the Gate::allows
method to check if the user has the specified ability, passing the $model
and $arguments
along with the $value
.
message()
The message
method returns the validation error message.
setValidator($validator)
The setValidator
method sets the current validator instance.
-
$validator
: The current validator instance.
<?php
namespace Illuminate\Validation\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Support\Facades\Gate;
class Can implements Rule, ValidatorAwareRule
{
/**
* The ability to check.
*
* @var string
*/
protected $ability;
/**
* The arguments to pass to the authorization check.
*
* @var array
*/
protected $arguments;
/**
* The current validator instance.
*
* @var \Illuminate\Validation\Validator
*/
protected $validator;
/**
* Constructor.
*
* @param string $ability
* @param array $arguments
*/
public function __construct($ability, array $arguments = [])
{
$this->ability = $ability;
$this->arguments = $arguments;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$arguments = $this->arguments;
$model = array_shift($arguments);
return Gate::allows($this->ability, array_filter([$model, ...$arguments, $value]));
}
/**
* Get the validation error message.
*
* @return array
*/
public function message()
{
$message = $this->validator->getTranslator()->get('validation.can');
return $message === 'validation.can'
? ['The :attribute field contains an unauthorized value.']
: $message;
}
/**
* Set the current validator.
*
* @param \Illuminate\Validation\Validator $validator
* @return $this
*/
public function setValidator($validator)
{
$this->validator = $validator;
return $this;
}
}