-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
ValidationServiceProvider.php
90 lines (79 loc) · 2.34 KB
/
ValidationServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
declare(strict_types=1);
namespace Intervention\Validation\Laravel;
use Illuminate\Support\ServiceProvider;
use Intervention\Validation\Exceptions\NotExistingRuleException;
use Intervention\Validation\Rule;
class ValidationServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
// load translation files
$this->loadTranslationsFrom(
__DIR__ . '/../lang',
'validation'
);
// add rules to laravel validator
foreach ($this->ruleShortnames() as $rulename) {
$this->app['validator']->extend(
$rulename,
function ($attribute, $value, $parameters, $validator) use ($rulename) {
return $this->interventionRule($rulename, $parameters)
->isValid($value);
},
$this->errorMessage($rulename)
);
}
}
/**
* Return rule object for given shortname
*
* @param string $rulename
* @param array<mixed> $parameters
* @return Rule
* @throws NotExistingRuleException
*/
private function interventionRule(string $rulename, array $parameters): Rule
{
$classname = sprintf("Intervention\Validation\Rules\%s", ucfirst($rulename));
if (!class_exists($classname)) {
throw new NotExistingRuleException("Rule " . $rulename . " does not exist.");
}
return new $classname($parameters);
}
/**
* List all shortnames of Intervention validation rule objects
*
* @return array<string>
*/
private function ruleShortnames(): array
{
return array_map(function ($filename) {
return mb_strtolower(substr($filename, 0, -4));
}, array_diff(scandir(__DIR__ . '/../Rules'), ['.', '..']));
}
/**
* Return error message of given rule shortname
*
* @param string $rulename
* @return string
*/
protected function errorMessage(string $rulename): string
{
return $this->app['translator']->get('validation::validation.' . $rulename);
}
/**
* Return the services provided by the provider.
*
* @return array<string>
*/
public function provides()
{
return ['validator'];
}
}