Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Last active November 4, 2021 16:50
Show Gist options
  • Save kmuenkel/29be3c1b6363f69503fb54124ff82bde to your computer and use it in GitHub Desktop.
Save kmuenkel/29be3c1b6363f69503fb54124ff82bde to your computer and use it in GitHub Desktop.
Link custom Rule class message() dynamic output to Validator Facade extensions.
<?php
class AppServiceProvider
{
...
/**
* @param string[] $rules
*/
protected function loadCustomValidationRules(array $rules)
{
foreach ($rules as $name => $ruleClass) {
//Logically, a string by-reference variable should work for this, but it's disallowed in this context
$message = new class {
/**
* @var Validator|null
*/
public static $validator;
/**
* @var Rule|null
*/
public static $rule;
/**
* @var string[]
*/
public static $parameters = [];
/**
* @var mixed
*/
public static $attribute = null;
/**
* @var string
*/
public static $ruleName = '';
/**
* @return string
*/
public function __toString()
{
return static::$validator->makeReplacements(
static::$rule->message(),
static::$attribute,
static::$ruleName,
static::$parameters
);
}
};
$message::$rule = $custom = app($ruleClass);
$instance = null;
//Intercept the arguments passed to the Rule::passes() method
$extension = function ($attribute, $value, $parameters, Validator $validator) use ($custom, $message) {
$message::$validator = $validator;
$message::$attribute = $attribute;
$message::$parameters = $parameters;
return $custom->passes($attribute, $value, $parameters, $validator);
};
//ValidatorFacade::replacer() would result in infinite recursion when using Validator::makeReplacements()
ValidatorFacade::extend($message::$ruleName = $name, $extension, $message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment