Skip to content

Commit

Permalink
[10.x] Use translator from validator in Can and Enum rules (#49251)
Browse files Browse the repository at this point in the history
* [10.x] Use translator from validator in `Can` and `Enum` rules

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
fancyweb and taylorotwell committed Dec 5, 2023
1 parent d0d57da commit fd208de
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
25 changes: 23 additions & 2 deletions src/Illuminate/Validation/Rules/Can.php
Expand Up @@ -3,9 +3,10 @@
namespace Illuminate\Validation\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Support\Facades\Gate;

class Can implements Rule
class Can implements Rule, ValidatorAwareRule
{
/**
* The ability to check.
Expand All @@ -21,6 +22,13 @@ class Can implements Rule
*/
protected $arguments;

/**
* The current validator instance.
*
* @var \Illuminate\Validation\Validator
*/
protected $validator;

/**
* Constructor.
*
Expand Down Expand Up @@ -56,10 +64,23 @@ public function passes($attribute, $value)
*/
public function message()
{
$message = trans('validation.can');
$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;
}
}
25 changes: 23 additions & 2 deletions src/Illuminate/Validation/Rules/Enum.php
Expand Up @@ -3,9 +3,10 @@
namespace Illuminate\Validation\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use TypeError;

class Enum implements Rule
class Enum implements Rule, ValidatorAwareRule
{
/**
* The type of the enum.
Expand All @@ -14,6 +15,13 @@ class Enum implements Rule
*/
protected $type;

/**
* The current validator instance.
*
* @var \Illuminate\Validation\Validator
*/
protected $validator;

/**
* Create a new rule instance.
*
Expand Down Expand Up @@ -56,10 +64,23 @@ public function passes($attribute, $value)
*/
public function message()
{
$message = trans('validation.enum');
$message = $this->validator->getTranslator()->get('validation.enum');

return $message === 'validation.enum'
? ['The selected :attribute is invalid.']
: $message;
}

/**
* Set the current validator.
*
* @param \Illuminate\Validation\Validator $validator
* @return $this
*/
public function setValidator($validator)
{
$this->validator = $validator;

return $this;
}
}

0 comments on commit fd208de

Please sign in to comment.