1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Pixelpeter\IsoCodesValidation; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\ServiceProvider; |
6
|
|
|
use Illuminate\Support\Str; |
7
|
|
|
|
8
|
|
|
class IsoCodesValidationServiceProvider extends ServiceProvider |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Bootstrap the application services. |
12
|
|
|
* |
13
|
|
|
* @return void |
14
|
|
|
*/ |
15
|
|
|
public function boot() |
16
|
|
|
{ |
17
|
|
|
// load translation files |
18
|
|
|
$this->loadTranslationsFrom( |
19
|
|
|
__DIR__.'/../lang', |
20
|
|
|
'validation' |
21
|
|
|
); |
22
|
|
|
|
23
|
|
|
// registering intervention validator extension |
24
|
|
|
$this->app['validator']->resolver(function ($translator, $data, $rules, $messages, $customAttributes) { |
25
|
|
|
// set the validation error messages |
26
|
|
|
foreach (get_class_methods('Pixelpeter\IsoCodesValidation\IsoCodesValidator') as $method) { |
27
|
|
|
$key = $this->getTranslationKeyFromMethodName($method); |
28
|
|
|
|
29
|
|
|
$messages[$key] = $this->getErrorMessage($translator, $messages, $key); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
return new IsoCodesValidator($translator, $data, $rules, $messages, $customAttributes); |
33
|
|
|
}); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Return translation key for correspondent method name |
38
|
|
|
* |
39
|
|
|
* @param string $name |
40
|
|
|
* @return string |
41
|
|
|
*/ |
42
|
|
|
private function getTranslationKeyFromMethodName($name) |
43
|
|
|
{ |
44
|
|
|
return Str::snake(substr($name, 8)); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Return the matching error message for the key |
49
|
|
|
* |
50
|
|
|
* @param string $key |
51
|
|
|
* @return string |
52
|
|
|
*/ |
53
|
|
|
private function getErrorMessage($translator, $messages, $key) |
54
|
|
|
{ |
55
|
|
|
// return error messages passed directly to the validator |
56
|
|
|
if (isset($messages[$key])) { |
57
|
|
|
return $messages[$key]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
// return error message from validation translation file |
61
|
|
|
if ($translator->has("validation.{$key}")) { |
62
|
|
|
return $translator->get("validation.{$key}"); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
// return packages default message |
66
|
|
|
return $translator->get("validation::validation.{$key}"); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Register the application services. |
71
|
|
|
* |
72
|
|
|
* @return void |
73
|
|
|
*/ |
74
|
|
|
public function register() |
75
|
|
|
{ |
76
|
|
|
// |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|