1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Flugg\Responder; |
4
|
|
|
|
5
|
|
|
use Flugg\Responder\Contracts\ErrorMessageResolver as ErrorMessageResolverContract; |
6
|
|
|
use Illuminate\Translation\Translator; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* A resolver class responsible for resolving messages from error codes. |
10
|
|
|
* |
11
|
|
|
* @package flugger/laravel-responder |
12
|
|
|
* @author Alexander Tømmerås <[email protected]> |
13
|
|
|
* @license The MIT License |
14
|
|
|
*/ |
15
|
|
|
class ErrorMessageResolver implements ErrorMessageResolverContract |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* A serivce for resolving messages from language files. |
19
|
|
|
* |
20
|
|
|
* @var \Illuminate\Translation\Translator |
21
|
|
|
*/ |
22
|
|
|
protected $translator; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* A list of registered messages mapped to error codes. |
26
|
|
|
* |
27
|
|
|
* @var array |
28
|
|
|
*/ |
29
|
|
|
protected $messages = []; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Construct the resolver class. |
33
|
|
|
* |
34
|
|
|
* @param \Illuminate\Translation\Translator $translator |
35
|
|
|
*/ |
36
|
58 |
|
public function __construct(Translator $translator) |
37
|
|
|
{ |
38
|
58 |
|
$this->translator = $translator; |
39
|
58 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Register a message mapped to an error code. |
43
|
|
|
* |
44
|
|
|
* @param mixed $errorCode |
45
|
|
|
* @param string $message |
46
|
|
|
* @return void |
47
|
|
|
*/ |
48
|
1 |
|
public function register($errorCode, string $message) |
49
|
|
|
{ |
50
|
1 |
|
$this->messages = array_merge($this->messages, is_array($errorCode) ? $errorCode : [ |
51
|
1 |
|
$errorCode => $message, |
52
|
|
|
]); |
53
|
1 |
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Resolve a message from the given error code. |
57
|
|
|
* |
58
|
|
|
* @param mixed $errorCode |
59
|
|
|
* @return string|null |
60
|
|
|
*/ |
61
|
3 |
|
public function resolve($errorCode) |
62
|
|
|
{ |
63
|
3 |
|
if (key_exists($errorCode, $this->messages)) { |
64
|
1 |
|
return $this->messages[$errorCode]; |
65
|
|
|
} |
66
|
|
|
|
67
|
2 |
|
if ($this->translator->has($errorCode = "errors.$errorCode")) { |
68
|
1 |
|
return $this->translator->get($errorCode); |
|
|
|
|
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
return null; |
72
|
|
|
} |
73
|
|
|
} |