Created
August 20, 2021 13:54
-
-
Save acrossoffwest/81db1e19032b7aa26f1b8ba29341213b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Rules\Contracts; | |
use Closure; | |
use Illuminate\Contracts\Validation\Rule; | |
interface RuleClosureContract extends Rule | |
{ | |
public function getPassesClosure(): Closure; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use App\Rules\Contracts\RuleClosureContract; | |
use Illuminate\Contracts\Validation\Rule; | |
use Illuminate\Support\Facades\Validator; | |
use Illuminate\Support\ServiceProvider; | |
use Illuminate\Support\Str; | |
class ValidatorServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Register any application services. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
} | |
/** | |
* Bootstrap any application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
$this->loadRules(); | |
} | |
private function loadRules() | |
{ | |
$dir = load_class_names_from_dir(app_path('Rules')); | |
if (empty($dir)) { | |
return; | |
} | |
$namespace = 'App\\Rules\\'; | |
foreach ($dir as $className) { | |
$fullClassName = $namespace.$className; | |
/** @var Rule|RuleClosureContract $instance */ | |
$instance = new $fullClassName(); | |
$ruleName = property_exists($instance, 'key') ? $instance->key : Str::snake($className); | |
Validator::extend($ruleName, $instance->getPassesClosure(), $instance->message()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment