Skip to content

Commit

Permalink
[6.x] Allow formatting an implicit attribute using a closure (#31246)
Browse files Browse the repository at this point in the history
*          allow formatting an implicit attribute using a closure
  • Loading branch information
themsaid authored and taylorotwell committed Jan 27, 2020
1 parent dc2b6cc commit 86dc9df
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Illuminate/Validation/Concerns/FormatsMessages.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,9 @@ public function getDisplayableAttribute($attribute)
// an implicit attribute we will display the raw attribute's name and not
// modify it with any of these replacements before we display the name.
if (isset($this->implicitAttributes[$primaryAttribute])) {
return $attribute;
return ($formatter = $this->implicitAttributesFormatter)
? $formatter($attribute)
: $attribute;
}

return str_replace('_', ' ', Str::snake($attribute));
Expand Down
20 changes: 20 additions & 0 deletions src/Illuminate/Validation/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ class Validator implements ValidatorContract
*/
protected $implicitAttributes = [];

/**
* The callback that should be used to format the attribute.
*
* @var callable|null
*/
protected $implicitAttributesFormatter;

/**
* The cached data for the "distinct" rule.
*
Expand Down Expand Up @@ -1112,6 +1119,19 @@ public function addCustomAttributes(array $customAttributes)
return $this;
}

/**
* Set the callback that used to format an implicit attribute..
*
* @param callable|null $formatter
* @return $this
*/
public function setImplicitAttributesFormatter(callable $formatter = null)
{
$this->implicitAttributesFormatter = $formatter;

return $this;
}

/**
* Set the custom values on the validator.
*
Expand Down
17 changes: 17 additions & 0 deletions tests/Integration/Validation/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,23 @@ public function testExists()
$this->assertFalse($validator->passes());
}

public function testImplicitAttributeFormatting()
{
$translator = new Translator(new ArrayLoader, 'en');
$translator->addLines(['validation.string' => ':attribute must be a string!'], 'en');
$validator = new Validator($translator, [['name' => 1]], ['*.name' => 'string']);

$validator->setImplicitAttributesFormatter(function ($attribute) {
[$line, $attribute] = explode('.', $attribute);

return sprintf('%s at line %d', $attribute, $line + 1);
});

$validator->passes();

$this->assertEquals('name at line 1 must be a string!', $validator->getMessageBag()->all()[0]);
}

protected function getValidator(array $data, array $rules)
{
$translator = new Translator(new ArrayLoader, 'en');
Expand Down

0 comments on commit 86dc9df

Please sign in to comment.